简体   繁体   English

Express.js GET 请求,无法允许 CORS

[英]Express.js GET Requests, Unable To Allow CORS

I have an express.js server with some cors allow origin code:我有一个带有一些 cors 允许原始代码的 express.js 服务器:

var express = require('express');

var app = express();
var router = express.Router();
require('dotenv').config()
const bodyParser = require('body-parser')

const cors = require("cors");
const corsOptions = {
  origin: '*',
  credentials: true,
  optionSuccessStatus: 200,
}

var allowedOrigins = ['http://localhost:4200',
                      'http://yourapp.com'];
app.use(cors({  
  origin: function(origin, callback){
    // allow requests with no origin     
    // (like mobile apps or curl requests)    
    if(!origin) 
      return callback(null, true);    
    if(allowedOrigins.indexOf(origin) === -1){
      var msg = 'The CORS policy for this site does not ' +                
          'allow access from the specified Origin.';      
      return callback(new Error(msg), false);    
    }    
    return callback(null, true);  
  }
}));

router.use(cors(corsOptions))

// router.use(bodyParser.urlencoded({ extended: true }))

// parse application/json
// router.use(bodyParser.json())

router.use(function (req, res, next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});

router.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();
});

router.get('/p', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

I then call a post request.然后我调用一个post请求。 It works!!有用!!

this.http.post<any>('http://localhost:3000/stuff', {
      dataToSend: docToStore
    }).subscribe({
      next: async data => {

        console.log('got some data back! ', data);

      },
      error: error => {
 
      }
    })

However, when I try to call any GET request... I get a cors error.但是,当我尝试调用任何 GET 请求时...出现 cors 错误。 wtf???卧槽??? Can anyone explain this??谁能解释一下这个??

this.http.get<any>('http://localhost:3000/p', {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*' }
    }).subscribe({
      next: async data => {
       
        console.error('ok ', data);

      },
      error: error => {
        
        console.error('There was an error ', error);
      }
    })

I am so completely baffled.我完全不知所措。 This makes literally no sense...这完全没有意义......

The Access-Control-Allow-* headers do not belong in a GET (or POST) request , they occur in responses . Access-Control-Allow-*标头不属于 GET(或 POST)请求,它们出现在响应中 And the unexpected Access-Control-Allow-Origin header is perhaps the reason why your GET request leads to a CORS error.意外的Access-Control-Allow-Origin标头可能是您的 GET 请求导致 CORS 错误的原因。

You have three places in your code that influence CORS:您的代码中有三个影响 CORS 的地方:

  • app.use(cors(...))
  • router.use(cors(...))
  • router.use(function(...)) that sets the Access-Control-Allow-* headers directly. router.use(function(...))直接设置Access-Control-Allow-*标头。

You should use only of these (preferably the first or second).您应该只使用这些(最好是第一个或第二个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM