provoter33
provoter33

Reputation: 119

How add headers on json-server?

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.

Upvotes: 5

Views: 7168

Answers (1)

Deepak Jha
Deepak Jha

Reputation: 1609

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

Upvotes: 4

Related Questions