我正在做一个Angular项目。我需要从Angular应用测试API调用,但无法正常工作。它返回我错误,
在以下位置访问XMLHttpRequest 来源为“ http://...../api/v1/user/authen” “ http:// localhost:4200”已被CORS政策阻止:对 预检请求未通过访问控制检查:它没有 HTTP正常状态。
在服务器上已经设置了 Access-Control-Allow-Origin:'*'
我还制作了一个简单的html + Jquery文件来测试调用API,并且效果很好。
function callApi(){
$.ajax({
type: "POST",
url: 'http://..../api/v1/user/authen',
data: {
"user": "admin",
"password": "123456"
},
success: function(data){
console.log(data);
},
});
}
但是从Angular APP中我仍然收到错误。我需要在Angular应用上专门设置任何内容吗?
答案 0 :(得分:1)
这可能是服务器本身的问题,不允许访问API形式localhost:4200.
您可以通过禁用Google chrome安全性来运行您的应用,然后尝试使用API。
打开“在Windows计算机中运行”,然后粘贴以下链接以禁用网络安全性并尝试使用API。
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
--disable-web-security --user-data-dir="C:\tmpChromeSession"
答案 1 :(得分:0)
我不清楚,但是我通过在负载中添加 JSON.stringify()来解决此问题。
login(credential) : Observable<any> {
return this.http.post<any>(
this.baseUrl + '/user/authen', JSON.stringify(credential)
)
.pipe(
map( res => res ),
catchError( this.handleError )
);
}