【发布时间】:2019-04-02 07:53:48
【问题描述】:
我正在使用带有 Axios 的 Vue JS 2.5:
"vue": "^2.5.17",
"vue-axios": "^2.1.4",
"axios": "^0.18.0",
我正在尝试像这样进行 POST 调用:
const data = querystring.stringify({
'email': email,
'password': password,
'crossDomain': true, //optional, added by me to test if it helps but it doesn't help
});
var axiosConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
// "Access-Control-Allow-Origin": "*",
'Accept': '*',
}
};
axios.post(url, data, axiosConfig)
.then((response) => {
console.log('response');
console.log(response);
})
.catch((error) => {
console.log('error');
console.log(error);
});
我也试过没有“axiosConfig”参数。但每次它进入捕获时,都会显示以下消息:Error: Network Error
在浏览器的网络选项卡中,我得到一个 200 状态和一个良好的响应(带有有效的 json),它基本上可以工作,但 Axios 返回错误并且没有响应。
控制台也输出此警告:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://url/api/page. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
我尝试从 Postman 打同样的电话,但效果很好。不同之处在于 Axios 使用我的 localhost:8080 发送标头:“Origin”和“Referrer”,这与我正在调用的 API url 不同。
如何从 axios 进行此调用而不会出现此错误?谢谢。
编辑
如果我使用 PHP,它可以工作:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://myurl",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundaryTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\nemail\r\n------WebKitFormBoundaryTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\npassword\r\n------WebKitFormBoundaryTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"Postman-Token: 62ad07e5",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundaryTrZu0gW",
"email: email",
"password: password"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
我只是复制粘贴了生成的 Postman 调用,然后从另一个页面尝试了它,它运行良好。所以这不是 CORS 问题,而是我的 Javascript 调用的问题。
【问题讨论】:
-
通过更改 服务器 以允许跨源资源共享 (CORS)
-
如果我使用 Postman 从本地主机发送帖子,它就可以工作。这不是服务器配置问题。和Axios有关。
-
不,它与 Axios 无关......邮递员不需要 CORS 来工作 - 阅读关于 CORS
-
真的吗?不知道。我会做更多的检查(使用普通的 JS 调用而不是 axios)并回复你的评论。
-
你在后台使用什么?
标签: javascript vue.js npm vuejs2 axios