【发布时间】:2020-05-22 18:15:23
【问题描述】:
我正在构建 Angular 8 应用程序(使用 localhost:4200),这个应用程序应该使用不同的端点(如 localhost:5000/contacts)从另一个应用程序(NodeJS 应用程序,使用 localhost:5000)获取和发布一些 JSON 数据.当我打电话给 localhost:5000/contacts 时——我收到一个错误
我试图做以下事情来解决这个错误:
1)我在我的数据源应用程序的响应中添加了标题:
router.get("/contacts", async (req: Request, res: Response) => {
const contactsGetResponse = accountingApi.getContacts(req.session.activeTenant.tenantId);
res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
res.header('Access-Control-Allow-Methods', 'GET,PUT,OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, \n' +
'Origin, Authorization, Accept, Client-Security-Token, Accept-\n' +
'Encoding, X-Auth-Token, content-type');
}
2)在调用api的函数中添加头文件:
public getContacts(){
public corsHeaders = new HttpHeaders({
'Content-Type': 'application/json;charset=utf-8',
'Accept': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:5000/'
});
let httpOptions;
httpOptions = {
headers: this.corsHeaders
};
const url = environment.myEndpoint + '/contacts';
return this.httpClient.get(environment.myEndpoint + '/contacts', httpOptions);
} 但我仍然得到这个错误。 我知道这里已经有很多类似的问题。但没有什么对我有用。有人可以帮我吗?
【问题讨论】:
标签: node.js angular http-headers