5

I have frontend and backend on different servers. I need make crossdomain request.

On localhost:4200 i use angular2. On localhost:3000 i use json-server. Еhe server should give the header:

Access-Control-Allow-Origin: *

But I do not know how to turn it on.

provoter33
  • 119
  • 2
  • 7
  • If it's just for local development, the simplest solution would be a chrome extension (Assuming you're using chrome) like this: https://chrome.google.com/webstore/detail/moesif-origin-cors-change/digfbfaphojjndkpccljibejjbppifbc This lets you define cors without changing your client or server code. – Aviv Shaked Dec 17 '17 at 16:18
  • The docs you linked to say CORS is enabled by default – user184994 Dec 17 '17 at 16:19

1 Answers1

4

try adding this in your server.js file, this code precisely will make your server cors enabled and then you will be able to send correct response. Mind about your variable names, and port number rest everything should be identical,

var express = require('express'),
   app = express(),
   port = process.env.PORT || 8080;

app.listen(port);
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});
Deepak Jha
  • 1,539
  • 12
  • 17
  • Is the server.js file supposed to contain other code? How does this server.js file actually get accessed? I don't understand how to get this to work. – Matt123 Nov 08 '19 at 19:42
  • yes it can contain other codes as well. Such as middleware or express or other framework. You can check for the basic express based project and see how that come along – Deepak Jha Nov 11 '19 at 05:31