typescript Angular 6 - 请求的资源上不存在“Access-Control-Allow-Origin”标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50448981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:25:29  来源:igfitidea点击:

Angular 6 - No 'Access-Control-Allow-Origin' header is present on the requested resource

node.jsangulartypescriptexpressangular6

提问by mittal bhatt

I have an Angular 6 project, which has a service with is pointing to a server.js

我有一个 Angular 6 项目,它有一个指向 server.js 的服务

Angular is on port: 4200 and Server.js is on port: 3000.

When I point the service to http://localhost:3000/api/posts(Server.js location), I'm getting this error:

当我将服务指向http://localhost:3000/api/posts(Server.js 位置)时,出现此错误:

Failed to load http://localhost:3000/api/posts: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Here is the server.js code:

这是 server.js 代码:

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

// Get our API routes
const api = require('./server/routes/api');

const app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/myproject/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

My question is:

我的问题是:

How to I get server.js to allow this call?

如何让 server.js 允许这个调用?

回答by Chiien

Great! you need to enable domain CORS that can make requests! You can try that

伟大的!您需要启用可以发出请求的域 CORS!你可以试试

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
"Access-Control-Allow-Origin", "*" -> used to accept all domains

Or you can just set localhost:4200or something like that

或者你可以设置localhost:4200或类似的东西

Try that and tell me if worked! Thanks! Hope this helps!

试试看,告诉我是否有效!谢谢!希望这可以帮助!

回答by mittal bhatt

If you are using Express, you can try this cors package.

EDIT:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

回答by Ronnie

Since you are using express, you could create a middleware and use it to redirect all your endpoints. Here is a working snippet of the same:

由于您使用的是 express,您可以创建一个中间件并使用它来重定向所有端点。这是相同的工作片段:

app.use((req,res,next) => {

     res.header("Access-Control-Allow-Origin","*");
     res.header("Access-Control-Allow-Methods", "POST, GET");
     res.header("Access-Control-Allow-Header","Origin, X-Requested-With, Content-Type, Accept");
     next();

})

Place it before you are setting your routes and you should be good.

把它放在你设置路线之前,你应该很好。

Check out: https://github.com/ronnielivingsince1994/phoenix/blob/master/messageboard/backend/server.jsfor understanding usage of middlewares in routing endpoints using express.js.

查看:https: //github.com/ronnielivingsince1994/phoenix/blob/master/messageboard/backend/server.js了解中间件在使用 express.js 的路由端点中的用法。