Handling Cross-Origin Resource Sharing Issues

  1. Using JSONP to Address Cross-Origin Problems (Not Recommended)

router.get('/', function(req, res, next) {
  let _callback = req.query.callback
  let { limitNum, pageCode } = req.query;
  limitNum = limitNum * 1 || 10
  pageCode = pageCode * 1 || 0
  sql.paging(User, {}, {_id: 0}, limitNum, pageCode).then(data => {
    var payload = {
      code: '200',
      message: 'success',
      data: data
    }
    if (_callback) {
      res.type('text/javascript'); 
      res.send(_callback + '(' + JSON.stringify(payload) + ')');
    } else {
      res.json(payload)
    }
  })
});
$.ajax({
  url: 'http://localhost:3000/users',
  dataType: 'jsonp',
  success: function (data) {
    console.log(data)
  }
})
  1. Implementing CORS for Cross-Origin Handling (Recommended Approach)

// Add to app.js
var allowCrossDomain = function (req, res, next) { 
  res.header('Access-Control-Allow-Origin', '*');
  next(); 
}; 
app.use(allowCrossDomain);
// No additional configuration needed for the endpoint
router.get('/', function(req, res, next) {
  let { limitNum, pageCode } = req.query;
  limitNum = limitNum * 1 || 10
  pageCode = pageCode * 1 || 0
  sql.paging(User, {}, {_id: 0}, limitNum, pageCode).then(data => {
    res.send({
      code: '200',
      message: 'success',
      data: data
    })
  })
});
$.ajax({
  url: 'http://localhost:3000/users',
  success: function (data) {
    console.log(data)
  }
})
  1. Resolvign Cross-Origin Issues via Reverse Proxy

Create vue.config.js at the project root:

// Single reverse proxy --- requires server restart
module.exports = {
  devServer: {
    proxy: 'http://localhost:3000'
  }
}
// Request path /pro → http://localhost:3000/pro
axios.get('/pro').then(res => {
  console.log(res)
  this.prolist = res.data.data
})

Tags: Cross-Origin cors JSONP Proxy web-development

Posted on Wed, 07 Oct 2026 16:05:52 +0000 by clarket