最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How add headers on json-server? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Dec 17, 2017 at 16:14 provoter33provoter33 1192 silver badges7 bronze badges 2
  • If it's just for local development, the simplest solution would be a chrome extension (Assuming you're using chrome) like this: chrome.google./webstore/detail/moesif-origin-cors-change/… This lets you define cors without changing your client or server code. – Aviv Shaked Commented Dec 17, 2017 at 16:18
  • The docs you linked to say CORS is enabled by default – user184994 Commented Dec 17, 2017 at 16:19
Add a ment  | 

1 Answer 1

Reset to default 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();
});
发布评论

评论列表(0)

  1. 暂无评论