0

I want to enable the cors in my nodejs.
Can someone say how I can do that?
Where and what should I change?

I wanted to publish my link via Heroku. But i can only use the get, post, put, delete if i put "https://cors-anywhere.herokuapp.com" before the existing link.

Thank you for helping me,

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 Answers1

1

You need to have middleware to pass cors, Which will allow origins

Use following Middleware after the message variable :

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

Note: if you want to allow only some origin or domain/IP replace '*'.

For Eg :

  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3636');
Naranz
  • 222
  • 1
  • 4