我有一个Angular 6项目,它的服务指向server.js
Angular is on port: 4200 and Server.js is on port: 3000.
当我将服务指向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.
这是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}`));
我的问题是:
如何让server.js允许此次通话?
答案 0 :(得分:4)
大!您需要启用可以发出请求的域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
或者你可以设置localhost:4200
或类似的东西
试试并告诉我是否有效!谢谢!希望这有帮助!
答案 1 :(得分:4)
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')
})
答案 2 :(得分:0)
由于您使用的是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();
})
将其放置在设置路线之前,你应该会很好。
签出:https://github.com/ronnielivingsince1994/phoenix/blob/master/messageboard/backend/server.js,以了解中间件在使用express.js路由端点时的用法。