【问题标题】:Browser Cancels PUT requests浏览器取消 PUT 请求
【发布时间】:2020-07-28 18:13:11
【问题描述】:

我有一个 rails api 和一个带有 axios 的 react 前端来与 api 交互。已在 Rails 中启用 CORS,但以下请求被浏览器取消,找不到原因。

请求被复制为“获取”调用:

fetch("http://localhost:3000/api/v1/profile", 
    {
        "credentials":"include",
        "headers":{
            "accept":"application/json, text/plain, */*",
            "accept-language":"en-GB,en-US;q=0.9,en;q=0.8",
            "authorization":"Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwic2NwIjoiYWNjb3VudCIsImF1ZCI6bnVsbCwiaWF0IjoxNTg2OTY4MjIwLCJleHAiOjE1ODcwNTQ2MjAsImp0aSI6IjhkNTE2YjIzLTA1MGQtNGU2MS04ZWE1LWM3ZGIwMzkxNTg0NCJ9.KuwtVNB5minrOs3lvfNjt7lVQSWNRXdqZsbErb6SrGM",
            "content-type":"application/json",
            "sec-fetch-dest":"empty",
            "sec-fetch-mode":"cors",
            "sec-fetch-site":"same-site"
        },
        "referrer":"http://localhost:3001/profile?",
        "referrerPolicy":"no-referrer-when-downgrade",
        "body":"{\"first_name\":\"testsdasd\",\"last_name\":\"asadeesdfsfs\"}",
        "method":"PUT",
        "mode":"cors"
}); 

这是否由于 CORS 而被取消?顺便说一句,其他帖子请求正在通过。

非常感谢。

下面是使用 axios 的代码。

async updateProfileData(profile) {
        try {
            let axiosResponse = await AxiosClient.instance().put('http://localhost:3000/api/v1/profile', {
                first_name: profile.first_name,
                last_name: profile.last_name
            },{
                headers: {
                    "Content-Type": "application/json"
                }
            });
            return axiosResponse;
        } catch (e) {
            return e.response;
        }
    }

【问题讨论】:

  • 代码显示的是 fetch,而不是 axios

标签: xmlhttprequest cors axios


【解决方案1】:

找到答案了。

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘http://localhost:3000/api/v1/profile’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’).

https://developer.mozilla.org/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials?utm_source=devtools&utm_medium=firefox-cors-errors&utm_campaign=default

【讨论】:

  • 浏览器似乎不接受带有 CORS 的授权标头。
  • 这能解决什么问题?那么 POST 是如何工作的呢?
  • 该帖子用于身份验证,不包含 Bearer 令牌。因此它通过了。
猜你喜欢
  • 2014-02-20
  • 2021-03-19
  • 2016-10-23
  • 2014-04-05
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
相关资源
最近更新 更多