[英]reactjs axios get request with custom header
我需要打这个电话
axios.get("http://127.0.0.1/myapi/test.php").then((response) => {
})
如果我执行此调用,一切正常且 HTTP 方法为 GET,但如果我更改为此
var config = {
headers: {"X-Id-Token": "abc123abc123"}
};
axios.get("http://127.0.0.1/myapi/test.php", config).then((response) => {
})
HTTP方法是OPTIONS,调用失败,为什么?
编辑
我正在使用节点(本地主机:3000)运行 reactjs 项目,并在 IIS 上调用 php api( http://127.0.0.1/myapi )
解决方案
Axios 客户端发出“ping”请求以检查地址是否可达。 所以,第一次调用是在 OPTIONS 方法中,后面的调用是在 GET 中。
axios({
url: 'http://127.0.0.1/myapi/test.php',
method: 'get',
headers: {
'X-Id-Token': 'abc123abc123',
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response)
})
.catch(err => {
console.log(err);
});
查看axios 拦截器以获得更通用的解决方案。 它允许您在每次发出请求时运行一个函数,这意味着您可以将标头配置移动到为任何请求调用的全局函数中。
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
Mayank Shukla 的好建议,这是一个 CORS 问题,我由此修改了我的 web.config
<add name="Access-Control-Allow-Origin" value="*" />
对此
<add name="Access-Control-Allow-Origin" value="http://localhost:3000" />
@Mauro Sala 您的 axios 请求是正确的。 您需要在服务器端允许您的自定义标头。 如果您在 php 中有您的 api,那么此代码将对您有用。
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD");
header("Access-Control-Allow-Headers: Content-Type, X-Id-Token");
一旦您允许在服务器端使用自定义标头,您的 axios 请求将开始正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.