我正在使用带有CLI 3.6.3的Vuejs,并且遇到了CORS问题,因此无法获取后端api数据。
错误消息是:
Access to XMLHttpRequest at 'http://...'
from origin 'http://localhost:8080'
has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
我确实创建了一个vue.config.js文件:
module.exports = {
devServer: {
proxy: 'https://my/site/myapi/myindex.php',
}
}
导入axios并声明crossDomain等于true:
import axios from "axios";
axios.defaults.crossDomain = true;
在后端我确实声明:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
如何在不遇到CORS问题的情况下访问后端api数据?
答案 0 :(得分:1)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *');
这应该是api接受请求的地方
答案 1 :(得分:0)
声明后:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
在后端的构造方法上,它开始起作用。