有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

ReactJS&Java:对飞行前请求的响应未通过访问控制检查

我正在使用axios从Java后端获取数据,但由于cors问题而失败(请查看附带的屏幕截图)。我注意到的一件事是,如果我注释掉axios文件中的AuthToken部分,它可以正常工作并给出状态200,如果我保留AuthToken,它会破坏cors的原因。不确定问题是在java代码中还是在我的axios中缺失了什么。js文件。我们将非常感谢您的帮助。提前谢谢

axios.js

import axios from "axios";

const instance = axios.create({
  baseURL: "https://abc.domain.com"
});

instance.defaults.headers.common["AuthToken"] =
"myAuthToken";

export default instance;

headers in .java file

 response.addHeader("Access-Control-Allow-Origin", "*");
 response.addHeader("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE");
 response.addHeader("Access-Control-Allow-Headers", "Content-Type, AuthToken");
 response.addHeader("Content-Type", "application/json");
 response.addHeader("Accept", "application/json");

Cors error screenshot


共 (2) 个答案

  1. # 1 楼答案

    错误是可以自我解释的

    No Access-Controll-Allow-Origin header

    你有其他标题,没错,但不是这个

    至于

    One thing i've noticed is that if i comment out AuthToken part in axios file, it works fine and gives status 200 and if i keep the AuthToken,

    这是因为普通GET被认为是“简单请求”,不适用于CORS限制。当您向请求添加额外的头时,它就不再简单了,CORS开始起作用

    有关简单请求的更多详细信息,请参见https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

  2. # 2 楼答案

    你会想看看这篇文章:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

    For requests without credentials, the literal value "*" can be specified, as a wildcard; the value tells browsers to allow requesting code from any origin to access the resource. Attempting to use the wildcard with credentials will result in an error.

    如您所见,您正在使用凭据传递请求。这就是为什么当你省略代币时它会起作用,但当你把它重新添加进去时它不会起作用。解决方案是在java端显式指定域,而不是使用*