【发布时间】:2020-01-02 00:08:59
【问题描述】:
我遇到了 cors 的问题。我无权访问服务器,提供第 3 方 API,但它确实使用正确的标头为我提供访问权限。我知道,因为原生 XHR 请求有效,只需放置要设置的 api 所需的授权和 client_id 标头。
无论如何,我无法让它与 Axios 一起工作,为此花了 3 天时间。如果有人帮助我,我会非常高兴!请看我在那里制作的一些 cmets 的代码。
这是本机 XHR 请求,有效:
var data = "{\"birthday\":\"1981-07-07\",\"email\":\"asdiiii@mail.com\",\"phone\":\"1234578901\"}";
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.response);
}
});
xhr.open("POST", "cross-url/api/detail");
xhr.setRequestHeader("authorization", "fake");
xhr.setRequestHeader("client_id", "fake");
xhr.setRequestHeader("content-type", "application/json");
xhr.send(data);
axios 代码,不起作用:
axios.defaults.headers.common['Accept'] = 'application/json, text/plain'
const instance = axios.create({
baseURL: 'cross-url',
// crossdomain:true, // this doesn't help
//mode:'cors', // this doesn't help too
/*
headers: {
'content-type':'application/json',
'client_id':'client_id_here',
'access-control-allow-origin':'*', // if I put this I get an error it's denied by 'access-control-allow-headers'
'Access-Control-Allow-Headers':
'Accept,Origin,Authorization,client_id,content-type,x-requested-with', // If I put this I get still an error that the header doesn't allow origin'
'Access-Control-Allow-Credentials': 'true',
},
*/
headers: {
'client_id':'fake',
},
transformRequest: [
(data,headers) => {
delete headers.common['X-CSRF-TOKEN']
console.log(data)
// return JSON.stringify(data) // this also doesn't work'
return data
},
],
});
instance.defaults.headers.common['authorization'] = 'fake';
const postData3 = {
email:'fake',
phone:'123123123',
birthday:'1981-07-07',
}
instance.post('/api/detail', postData3).then((response) => {
console.log(response)
}).catch((e) => {
console.log(e)
console.log(e.request)
})
【问题讨论】:
-
你得到什么错误?
-
Access-Control-Allow-*headers 是 response headers,不要继续请求。 -
如果我不放置任何标题,我会发现缺少“访问控制允许来源”。如果我输入 'access-control-allow-origin' 我会得到 'access-control-allow-headers' 不允许 'access-control-allow-origin',我把它放在 cmets 中。如何在响应标头中添加“access-control-*”?
-
您需要让 服务器 发送 CORS 标头。了解 CORS。
标签: vue.js cors xmlhttprequest axios