Javascript 外部API的CORS问题-通过PostMan工作,但不通过Axios的HTTP请求
正在进行一个新的Laravel项目,该项目涉及汽车数据,并找到了一个免费的查找APIJavascript 外部API的CORS问题-通过PostMan工作,但不通过Axios的HTTP请求,javascript,api,vue.js,axios,Javascript,Api,Vue.js,Axios,正在进行一个新的Laravel项目,该项目涉及汽车数据,并找到了一个免费的查找API http://www.carqueryapi.com/documentation/api-usage/ 一个示例端点是: https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes 这在具有正常GET请求的邮递员上运行良好 但是,在使用Axios的Vue.js中: getAllMakes: function() { axios.g
http://www.carqueryapi.com/documentation/api-usage/
一个示例端点是:
https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes
这在具有正常GET请求的邮递员上运行良好
但是,在使用Axios的Vue.js中:
getAllMakes: function() {
axios.get("https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes").then(function(response) {
console.log(response);
});
}
我有一个CORS问题:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
有什么我能做的吗?或者API正在阻止某些错误?您可以使用以下命令修复此错误
return axios(url, {
method: 'GET',
mode: 'no-cors',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
},
credentials: 'same-origin',
}).then(response => {
console.log(response);
})
请在API中添加cors中间件
<?php
namespace App\Http\Middleware;
use Closure;
class CORS {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
然后您可以在路由中使用此选项
Route::get('/', function () {`enter code here`
})->middleware('cors');
您需要设置Access Control Allow Origin标头。查看此链接了解更多信息,页面底部的标题信息:Cors问题是您的浏览器保护您,这就是为什么它不会在邮递员bc中失败,他们会忽略它。解决方案是,您需要在LaravelAPI中设置适当的头。有几种方法可以做到这一点,因此请参见@tam5:他在示例代码中使用的是Vue而不是Laravel。我个人认为,出于安全考虑,应该在服务器端而不是客户端获取API数据。也许这个演示api不需要凭据,但我相信,如果以后您想要获得真实数据,您需要根据api进行身份验证。然后问题是:您想让用户控制身份验证凭据吗?如果不在后端获取数据,则在vue组件中从后端获取数据。
Route::get('/', function () {`enter code here`
})->middleware('cors');