我在Angular 5项目中尝试从我的服务器获取令牌时遇到问题。我的const stream = through2.obj((chunk, enc, callback) => {
callback(null, parseString(chunk))
});
stream
.pipe(through2.obj((chunk, enc, callback) => {
callback(null, JSON.stringify(chunk));
}))
.pipe(process.stdout);
socket.on('m', data => stream.write(data));
请求永远不会被发送,服务器返回POST
并在控制台中显示以下内容:
我的理解是我需要在CORS中配置400 Bad Request
请求以允许跨源请求,但我觉得我已经尝试了所有解决方案,但没有任何成功。
至于我迄今为止所尝试的内容,在OPTIONS
我有这个:
我在Web.config
:
我甚至实施了https://www.stevefenton.co.uk/2012/11/using-cors-with-asp-net-web-api/
建议的解决方案以下是我在Angular 5项目中的电话:
WebApiConfig.cs
当我使用POSTMAN拨打电话时,一切运行顺利,我得到userAuthentication(userDetails: LoginUser): Observable<LoginUser> {
var data = "username=" + userDetails.username + "&password=" + userDetails.password + "&grant_type=password";
var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'No-Auth': 'True' });
return this.http.post<LoginUser>(this._baseUrl + 'Token', data, { headers: reqHeader })
.pipe(
catchError(this.handleError)
)
}
。
答案 0 :(得分:1)
我设法解决了这个问题。我需要使用Microsoft.Owin.Cors
和Microsoft.AspNet.Cors
添加Microsoft.AspNet.WebApi.Cors
。
然后,我必须将app.UseCors(CorsOptions.AllowAll);
添加到我的Startup.cs
文件中:
...并从customHeaders
中的system.webserver
代码中移除Web.config
:
现在一切顺利。
注意:请务必注意,在WebApiConfig.cs
启用CORS时,如果您已按照我之前显示的步骤操作,则必须按以下步骤启用:
......而不是这样:
如果您这样做,则会收到错误消息,指出您的标头包含多个值,因此会拒绝您Origin
访问。