如何在Node.js中启用Cors

时间:2019-04-04 18:26:01

标签: node.js cors-anywhere

我想在我的nodejs中启用cors。
有人可以说我该怎么做吗?
我应该在哪里更改什么?

我想通过Heroku发布链接。 但是我只能使用get,post,put,delete 现有链接之前的“ https://cors-anywhere.herokuapp.com”。

谢谢您的帮助,

const express = require('express');
const route = express.Router();
const messages = [
 {
   id: 1,
   user: "Pikachu",
   message: "pika pika"
 },
 {
   id: 2,
   user: "Ash",
   message: "I choose you!"
 },
 {
   id: 3,
   user: "Misty",
   message: "Can't drive, it's to misty"
 },

 {
   id: 911,
   user: "Emergency",
   message: "bee doo bee doo"
 } 
];

route.get('/', function(request, response, next) {

  // Render express index pagina
  response.render('index', { title: 'Lab 5' });
  response.end();
});


route.get('/api/v1/messages/:id', (request, response) => {

  // controleren of er een ID overeenkomt met een bestaande ID
  const message = messages.find(my_int => my_int.id === parseInt(request.params.id));


  if(!message){
    // geen message gevonden = foutmelding
    response.status(404).json({status:"error","message":"Message with ID " + request.params.id +" does not exist"})
  }
  else {
    // wel message gevongen = json doorsturen
    response.json({status:"success", message:"GETTING message with ID " + request.params.id});
  }
});


route.post('/api/v1/messages/', (request, response) => {

  const new_message = { id: request.params.id, user: 
  request.query.user, message: request.body.message };
  messages.push(new_message);
  response.json({ status:"success", message:"POSTING a new message 
  for user " + request.query.user});
});

module.exports = route;

1 个答案:

答案 0 :(得分:0)

您需要具有通过cors的中间件,这将允许起源

在消息变量之后使用以下中间件:

route.use(function(req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');

        // 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, Authorization');

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

注意:如果您只想允许某些来源或域/ IP,请替换'*'

例如:

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3636');