我的Nodejs restful服务有以下端点http://localhost:3000/api/countries。我正在使用这个中间件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
}));
我在位于 http://localhost:4200 的 Angular 6 应用程序中拥有以下代码。
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://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
};
}
我的React代码完美地实现了所需的响应,但是Angular 6出现了以下错误:-
“Access to XMLHttpRequest at 'http://localhost:3000/api/countries' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.”
请问我的Angular 6代码有什么问题?
请注意,我已经看到类似问题的答案,建议使用json文件(proxy.conf.json)作为代理服务器或安装Chrome扩展程序。这些对我来说都不是选项。
感谢您提供的帮助。