解决 axios 跨域时,发送 post 请求变 options 的问题
解决axios跨域时,发送post请求变options的问题
在使用vuejs开发前后端完全分离的项目时,都会使用跨域请求。在开发过程中就遇到这样的坑。直接上代码
let config = {
headers : {
'Content-Type':'application/json;charset=UTF-8'
},
};
axios.post(this.authUrl,JSON.stringify(this.userInfo),config)
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
上面的代码在请求之后的结果如下
Request URL:http://59.110.160.110:9990/login
Request Method:OPTIONS
Status Code:404 Not Found
Remote Address:59.110.160.110:9990
Referrer Policy:no-referrer-when-downgrade
Response Headersview source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Content-Encoding, Cache-Control,
Content-Length, Accept-Encoding, Authorization, Origin, X-Requested-With,
Accept
Access-Control-Allow-Methods:GET, POSTAccess-Control-Allow-Origin:*
Content-Length:18
Content-Type:text/plain
Date:Tue, 10 Oct 2017 08:58:57 GMT
Request Headers
view source
Accept:/
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:59.110.160.110:9990
Origin:http://localhost:8080
Referer:http://localhost:8080/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
上面的结果导致总是返回404 ,因为后台不允许options访问。
后来查询各种资料发现:根源在于,我们发出去的请求不是 simple request
,那么在每次发送请求之前,都会发送一个options请求,simple request
需要同时满足以下条件(规范可以百度查询):
- get、post、head 请求类型
- 不要设置列表之外的header(如: user-agent)
- Content-Type 只能是:
- application/x-www-from-urlencoded
- multipart/from-data
- text/plain
其他资料也说过,默认请求就是application/json
,所以不需要自己加上头部,现在上正确的代码:
axios.post(this.authUrl,JSON.stringify(this.userInfo))
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
可以看到,我们没有上面的config
的配置了。问题也就出在这里,OK问题解决
推荐文章: