简体   繁体   中英

CORS issue in express JS

I am getting cors error with this code. I have applied the cross origin headers too. Please tell me the solution for this.

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var router = express.Router();
app.use(bodyParser.json());

app.all('/*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
 });


router.get('/',function(req,res){
    res.send('Yippeee! You found me.');
});
router.post('/postTest',function(req,res){
    console.log(req.body);
    res.json(req.body);
});

app.use('/',router);

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

It's hard to give a specific answer because there's so many unknowns in your question. However you could give the CORS plugin a shot:

var cors = require('cors');

app.use(cors());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM