我已经在标题中添加了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', []))
);
}
Run Code Online (Sandbox Code Playgroud)
错误:
对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:4200 '访问
失败:(未知网址)的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');
Run Code Online (Sandbox Code Playgroud)