【问题标题】:I can't perform a request from ReactJS. The header can not be written correctly我无法执行来自 ReactJS 的请求。标头无法正确写入
【发布时间】:2020-03-02 09:17:26
【问题描述】:
axios.get('http://localhost:8080/omp/patients', { headers: {authorization: 'Bearer ' + token}})
        .then( response => {
                this.state = response.data;
            }
        ).catch(ex=> {
            alert("You are not registered");
            //console.log(e)
        });

在网络中,我有字段:“Access-Control-Request-Headers:授权”,但没有字段“授权:令牌”

【问题讨论】:

  • 看起来不错,你可以试试{ headers: { "Authorization": `Bearer ${token}` }}
  • 别工作! “从源 'localhost:3000' 访问 XMLHttpRequest 在 'localhost:8080/omp/patients' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。”

标签: reactjs spring security spring-security axios


【解决方案1】:

您需要正确设置 Authorization 标头,如上面的评论所示。

关于 CORS 政策的回复:

您将需要了解 CORS,但如果 Chrome 和其他浏览器在响应时没有设置正确的 CORS 标头,则它们基本上会停止网络请求。预检是在发送实际请求之前发送到同一 URL 以了解该 URL 是否支持 CORS 的初始请求。看起来服务器不理解 CORS 预检或配置不正确。

你有几个选择:

  1. 如果您有权访问服务器配置或代码(例如 Laravel 或 NodeJS 服务器),请安装 CORS 插件。
  2. 如果您是唯一使用此功能的用户,您可以安装适用于 Chrome 或 Firefox 等的 CORS 浏览器扩展。

【讨论】:

  • 我可以访问服务器。它是我用Java编写的。谢谢。我会尝试解决这个问题!
  • 优秀。我已经有一段时间没有使用 Java 服务器了,但我想有很多文章和指南可以在您的服务器中启用 CORS 支持。
  • 该错误是因为服务器抛出了异常。在服务器中,我尝试从授权字段中获取令牌。如果缺少标头“授权”,则会引发异常。为了检查这一点,我在该方法中对令牌进行了硬编码。
  • ``` public Authentication attemptAuthentication(... httpServletRequest, ... httpServletResponse) throws AuthenticationException { String header = httpServletRequest.getHeader("Authorization"); if(header == null || !header.startsWith("authorization")){ //这里我硬编码令牌 throw new RuntimeException("JWT Token is missing"); } String authenticationToken = header.substring(13);返回 getAuthenticationManager().authenticate(token); }```
【解决方案2】:

把你的代码改成这样:

axios.get('http://localhost:8080/omp/patients', { headers: { "Authorization": 'Bearer ' + token}})
        .then( response => {
                this.state = response.data;
            }
        ).catch(ex=> {
            alert("You are not registered");
            //console.log(e)
        });

同样在你的 app.js/index.js 中运行你的服务器 import/require cors 模块并这样做:

let cors = require('cors');
app.use(cors());

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2013-10-01
    • 2018-01-15
    • 2017-11-09
    • 2019-07-14
    • 2018-10-30
    相关资源
    最近更新 更多