我正在尝试向ERP API发出请求,我得到的响应是:
访问位于"的XMLHttpRequesthttp://ip:8082/auth'来自原点'http://connector.test'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在"access control Allow Origin"标头。
尽管在我的请求中有一个标题Access Control Allow Origin:
getAuth() {
axios.post('http://'+this.ip + '/auth/', {
headers: {
"Content-Type": "application/json",
"Cookie": this.sessionid,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length"
},
data: {
username: this.username,
password: this.password
}
}).then(response => {
this.getItems();
})
},
Cors.php
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
js/bootstrap.js
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
window.axios.defaults.headers.common['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE';
添加了我自己的中间件
中间件/cors.php
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE,
OPTIONS');
将其添加到kernel.php$routeMiddleware,然后添加到web.php
Route::get('/', [AppHttpControllersMainController::class, 'index'])->middleware(Cors::class);
请求标头
Request URL: http://ip:8082/auth
Referrer Policy: strict-origin-when-cross-origin
Provisional headers are shown
Accept: application/json, text/plain, */*
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin: *
Content-Type: application/json;charset=UTF-8
Referer: http://connector.test/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
X-Requested-With: XMLHttpRequest
用PHP Curl在后端处理请求很好,但我想用Vue在前端处理它。
Web浏览器有一个安全功能,可以阻止DOS对网站的大规模攻击。简而言之,任何在X上运行的代码都不能在Y上请求资源,除非Y特别允许X请求它。这是通过访问控制允许起源标头来完成的。
您必须将其添加到您的Web服务器或后端代码中。
试试这个。
axios.post('http://yourdomain.com', {
withCredentials: true,
// put the rest of your config here
})
我相信这是因为你把它们发送到服务器,但没有用withCredentials
标记,所以服务器不知道请求来自哪里,或者只是忽略它
这种情况也发生在我身上,这种方法对我有效