【发布时间】:2023-03-29 22:19:01
【问题描述】:
我已在标头中添加了 CORS,但我的请求中仍然存在 CORS 问题。在标头中添加和处理 CORS 和其他请求的正确方法是什么?
这里是服务文件代码:
import { HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin':'*',
'Authorization':'authkey',
'userid':'1'
})
};
public baseurl = 'http://localhost/XXXXXX';
userAPI(data): Observable<any> {
return this.http.post(this.baseurl, data, httpOptions)
.pipe(
tap((result) => console.log('result-->',result)),
catchError(this.handleError('error', []))
);
}
错误:
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:4200' 因此不允许访问
失败:(未知 url)的 Http 失败响应:0 未知错误
在我的服务器端代码中,我在索引文件中添加了 CORS。
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
【问题讨论】:
-
需要在服务端添加Cors header。
-
@SachilaRanawaka 是的,我已将它添加到我的索引文件中。
-
发布该服务器文件
-
这个答案可能有用:stackoverflow.com/a/58064366/7059557