Axios CORS 问题消费 API



我在使用cors时遇到了问题。我无权访问提供第三方 API 的服务器,但它确实使用正确的标头为我提供访问权限。我知道,因为本机 XHR 请求有效,只需放置授权和client_id标头,这是 api 需要设置的。

无论如何,我无法让它与 Axios 一起工作,为此花了 3 天时间。如果有人帮助我,我会很高兴!请查看我在那里发表的一些评论的代码。

这是本机 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-xxx 是服务器到客户端的标头,出于所有实际目的,没有服务器会接受它们。

关于可控硅量

删除 access-control.xxx 标头,然后查看响应。 如果被拒绝,服务器会通知您原因。

如果您无权访问服务器,并且您的主机、方法和/或客户端标头被拒绝,则您所能做的就是使用代理(将呼叫从浏览器转发到中间服务器(。 但是,您将需要访问某些服务器。

最新更新