node.js - Angular 6 - 请求的资源上不存在 'Access-Control-Allow-Origin' header

标签 node.js angular typescript express angular6

我有一个 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 允许此调用?

最佳答案

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')
})

关于node.js - Angular 6 - 请求的资源上不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50448981/

相关文章:

cordova - 在设备上运行需要服务器的 angular2 应用程序

angular - 将 jasmie .toHaveBeenCalledWith() 函数与 Moment 对象一起使用

javascript - 如何停止这个 React useEffect 中的无限循环?

javascript - 跨 React 组件使用自定义 api 客户端的惯用方法是什么?

node.js - NodeJS : Mongoose return wrong results from MongoDB although Mongo shell return correct ones

javascript - 我怎么知道连接是否安全?

d3.js - 是否有可能让 Angular2 和 D3.js 一起工作?

node.js - 编译 NodeJS 命令行应用程序

javascript - 无法通过 ember 安装 bourbon

angular - ng2-smart-table 中的复选框