【问题标题】:React JS - CORS Missing Allow Header when sending POST requestReact JS - 发送 POST 请求时 CORS 缺少允许标头
【发布时间】:2021-01-11 14:18:41
【问题描述】:

我在向我的 REST-API 发送 POST 请求时遇到了一些问题。

问题是,当我从 react 应用程序发送它时,它会在 firefox 的调试控制台中显示此错误。

有趣的是,当使用邮递员发送请求时,它工作得非常好。

这是我用来发出请求的代码:

let apiURL = API_URL_BASE + "/api/authenticate"
        let requestBody = JSON.stringify(
            {
                "username": this.getEnteredLoginUsername(),
                "password": this.getEnteredLoginPassword()
            }
        );
        let headerData = new Headers();
        headerData.append('Accept', '*');
        headerData.append("Access-Control-Allow", "*");
        headerData.append('Content-Type', 'application/json');
        headerData.append('Access-Control-Allow-Origin', '*');
        headerData.append("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
        headerData.append("Access-Control-Allow-Headers", "*");
        
        let requestOptions = {
            method: 'POST',
            mode: 'cors',
            redirect: 'follow',
            body: requestBody,
            headers: headerData
        }
        this.setState({loadingData: true});
        fetch(apiURL, requestOptions).then( response => {
            let responseStatus = response.status;
            response.json().then( responseJSON => {
            });
        });

我希望有人可以帮助我。

这是火狐控制台显示的错误:Image

【问题讨论】:

    标签: javascript http-post


    【解决方案1】:

    您似乎确实从客户端(即浏览器)获得了正确的请求标头,但是托管 API 的服务器也必须向客户端发送响应,表明它允许跨域请求,否则浏览器将不会继续处理您的请求。从服务器设置 cors 标头将取决于您用于后端的框架。实际上,您需要将在此处添加的那些 cors 标头添加到服务器代码中。

    示例响应标头如下所示:

    HTTP/1.1 200 OK
    Date: Mon, 01 Dec 2008 00:23:53 GMT
    Server: Apache/2
    Access-Control-Allow-Origin: * (Note: * means this will allow all domains to request to your server)
    Keep-Alive: timeout=2, max=100
    Connection: Keep-Alive
    Transfer-Encoding: chunked
    Content-Type: application/xml
    

    快递可以关注这个link

    更多关于 CORS here

    【讨论】:

    • 我使用 Spring boot 作为 REST-API,目前它运行在同一台机器上进行测试。你碰巧也知道弹簧靴吗?但你的回答肯定对我有帮助
    • 端口必须不同
    • 我不确定 spring boot 的确切代码,查看这里spring.io/guides/gs/rest-service-cors/…
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2021-11-10
    • 2022-10-18
    • 2021-11-27
    • 1970-01-01
    • 2021-12-13
    • 2018-11-02
    相关资源
    最近更新 更多