axios不发布数据跨域

时间:2017-03-20 12:19:51

标签: ajax http-headers cors axios

我无法将数据发布到服务器(其他域)。总是我尝试在身体中发送一些数据,我正在

  

对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头。

响应中有所需的cors标头,而且没有正文数据的每个GET请求和POST请求都正常工作。只有将数据发送到服务器才会出现此问题。

工作示例:

axios.post('https://some-server.com/')
.then(function (response) {
  console.log(response);
});

# getting the following headers in response (chrome dev-tools)

Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Cache-Control:no-cache, private
Connection:keep-alive
Content-Type:application/json
Date:Mon, 20 Mar 2017 12:17:35 GMT
Server:nginx/1.8.0
Transfer-Encoding:chunked
X-RateLimit-Limit:60
X-RateLimit-Remaining:59

不工作的例子:

axios.post('https://some-server.com/', {
  data : 'foobar'
})
.then(function (response) {
  console.log(response);
});

# getting the following headers in response (chrome dev-tools)

Allow:POST
Cache-Control:no-cache, private
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Mon, 20 Mar 2017 09:30:31 GMT
Server:nginx/1.8.0
Transfer-Encoding:chunked

标题在两种情况下都会得到回应(Postman):

Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin →*
Cache-Control →no-cache, private
Connection →keep-alive
Content-Type →application/json
Date →Mon, 20 Mar 2017 12:09:05 GMT
Server →nginx/1.8.0
Transfer-Encoding →chunked
X-RateLimit-Limit →60
X-RateLimit-Remaining →59

解决

我的解决方案是将数据作为FormData实例发送。

如果有人有时间,那么用axios.post的第二个参数知道幕后发生的事情会很好。

0 个答案:

没有答案