我已经在头中添加了CORS,但我仍然在我的请求中得到CORS问题。在headers中添加和处理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”标头。因此不允许访问源'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');
发布于 2017-12-22 06:12:18
根据我的经验,这些插件可以使用HTTP,但不能使用最新的httpClient。此外,在服务器上配置CORS响应头也不是一个真正的选择。因此,我创建了一个proxy.conf.json
文件作为代理服务器。这仅用于开发目的。
阅读有关此here的更多信息。
proxy.conf.json
文件:
{
"/posts": {
"target": "https://example.com",
"secure": true,
"pathRewrite": {
"^/posts": ""
},
"changeOrigin": true
}
}
我在同一目录中的package.json
文件旁边放置了proxy.conf.json
文件。
然后我修改了package.json文件中的启动命令:
"start": "ng serve --proxy-config proxy.conf.json"
来自我的应用程序组件的HTTP调用:
return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
console.log(returnedStuff);
});
最后,要运行我的应用程序,我必须使用npm start
或ng serve --proxy-config proxy.conf.json
发布于 2019-06-17 20:54:04
您还可以尝试使用fetch
函数和no-cors
模式。我有时发现它比Angular内置的http模块更容易配置。您可以右键单击Chrome Dev tools网络选项卡中的请求,并将其复制到fetch语法中,这很棒。
import { from } from 'rxjs';
// ...
result = from( // wrap the fetch in a from if you need an rxjs Observable
fetch(
this.baseurl,
{
body: JSON.stringify(data)
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
mode: 'no-cors'
}
)
);
发布于 2020-02-12 03:36:49
如果您像我一样,使用本地SMS网关服务器,并向192.168.0.xx之类的IP发出GET请求,您肯定会收到CORS错误。
不幸的是,我找不到Angular的解决方案,但在之前的重播的帮助下,我得到了我的解决方案,并发布了Angular 7 8 9的更新版本
import {from} from 'rxjs';
getData(): Observable<any> {
return from(
fetch(
'http://xxxxx', // the url you are trying to access
{
headers: {
'Content-Type': 'application/json',
},
method: 'GET', // GET, POST, PUT, DELETE
mode: 'no-cors' // the most important option
}
));
}
只是像往常一样使用.subscribe。
https://stackoverflow.com/questions/47345282
复制相似问题