簡體   English   中英

Angular 6 - 請求的資源上不存在“Access-Control-Allow-Origin”標頭

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

我有一個 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 允許這個調用?

偉大的! 您需要啟用可以發出請求的域 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或類似的東西

試試看,告訴我是否有效! 謝謝! 希望這可以幫助!

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

由於您使用的是 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/pyronlaboratory/phoenix/blob/master/messageboard/backend/server.js了解中間件在使用 express.js 的路由端點中的用法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM