我的 Nodejs Restful 服务有以下端点http://localhost:3000/api/countries http://localhost:3000/api/countries。我正在使用这个中间件https://github.com/expressjs/cors https://github.com/expressjs/cors。我已启用 cors,因此:-
const cors = require('cors');
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
我的 Angular 6 应用程序中有以下代码,托管于http://本地主机:4200 http://localhost:4200
import { HttpClient, HttpHeaders } from '@angular/common/http';
httpClient: HttpClient;
getCountries(): Observable<any> {
const url = 'http://localhost:3000/api/countries';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
})
};
return this.httpClient.get(url, httpOptions).pipe(
map((result: any) => {
return result;
})
);
}
我的 React 应用程序中有以下代码http://本地主机:3001 http://localhost:3001
getCountries() {
const url = 'http://localhost:3000/api/countries';
const init = {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
try {
const response = await fetch(url, init);
const json = await response.json();
return json
};
}
我的反应代码完美地给出了所需的响应,但 Angular 6 给出了以下错误:-
访问 XMLHttpRequest 位于 'http://localhost:3000/api/countries http://localhost:3000/api/countries' 从
起源 'http://本地主机:4200 http://localhost:4200' 已被 CORS 策略阻止:
请求头字段 access-control-allow-origin 不允许
预检响应中的 Access-Control-Allow-Headers。
我的 Angular 6 代码做错了什么?
请注意,我已经看到建议使用类似问题的答案
一个 json 文件 (proxy.conf.json),用作代理服务器或安装 chrome 扩展。这些对我来说不是选择。
预先感谢您的有用回复。