Angular 6 - 请求的资源上不存在“Access-Control-Allow-Origin"标头 [英] Angular 6 - No 'Access-Control-Allow-Origin' header is present on the requested resource

查看:31
本文介绍了Angular 6 - 请求的资源上不存在“Access-Control-Allow-Origin"标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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 代码:

Here is the server.js code:

// 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 允许这个调用?

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

推荐答案

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

这篇关于Angular 6 - 请求的资源上不存在“Access-Control-Allow-Origin"标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆