Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 2个本地应用之间的请求阻止跨来源请求_Node.js_Angular_Http Headers - Fatal编程技术网

Node.js 2个本地应用之间的请求阻止跨来源请求

Node.js 2个本地应用之间的请求阻止跨来源请求,node.js,angular,http-headers,Node.js,Angular,Http Headers,我正在构建Angular 8应用程序(使用localhost:4200),这个应用程序应该使用不同的端点(比如localhost:5000/contacts)从另一个应用程序(使用localhost:5000的NodeJS应用程序)获取并发布一些JSON数据。当我调用localhost:5000/contacts时,我得到一个错误 我试着做以下事情来解决这个错误: 1) 我在我的数据源应用程序的响应中添加了标题: router.get(“/contacts”),异步(req:Request,re

我正在构建Angular 8应用程序(使用localhost:4200),这个应用程序应该使用不同的端点(比如localhost:5000/contacts)从另一个应用程序(使用localhost:5000的NodeJS应用程序)获取并发布一些JSON数据。当我调用localhost:5000/contacts时,我得到一个错误 我试着做以下事情来解决这个错误: 1) 我在我的数据源应用程序的响应中添加了标题:
router.get(“/contacts”),异步(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-request-With,内容类型,\n'+
'来源,授权,接受,客户端安全令牌,接受-\n'+
'编码,X-Auth-Token,内容类型';
}
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);
} 但我还是犯了这个错误。
我知道这里已经提出了许多类似的问题。但对我来说什么都不管用。有人能帮我吗?

npm i cors
使用
app.Use(cors())
在后端,假设您使用的是
expressjs
app=express()
代码应该如下所示

const app = express()
const cors=require('cors')
app.use(cors())
app.get('/',(req,res)=>{
   res.send()
})


我应该为这两个应用程序安装cors吗?或者只针对其中一个?对于节点,仅后端似乎此解决方案对我有效-我安装了cors lib,将访问控制允许源标题放入响应。而且它似乎起作用了。将继续测试。