Express Set CORS, Let Browser Cross-Origin Access Your Server

Speaking of frontend cross-origin, it really makes many frontend developers sweat.

Cross-origin solutions are like eight immortals crossing the sea. Various black tech, various black magic. Makes people amazed. (If you don’t understand, you can search)

But none are perfect solutions, all can do this but not that.

Today I’ll talk about the ultimate cross-origin solution (IE8 and lower versions don’t support)

Cross-Origin Resource Sharing (CORS);

var express = require('express');  
var app = express();  
//Set CORS
app.all('*', function(req, res, next) {  
    res.header("Access-Control-Allow-Origin", "*");  
    //Second parameter is an asterisk, means pages from any domain can request this server;
    //Set specified domain:
    //res.header("Access-Control-Allow-Origin", "http://baidu.com");
    //This way, web pages under baidu.com can ajax request your server


    res.header("Access-Control-Allow-Headers", "X-Requested-With");  


    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
    //Second parameter is which HTTP request methods the other party can use to request your server, set according to your situation


    res.header("X-Powered-By",' 3.2.1')  
    res.header("Content-Type", "application/json;charset=utf-8");  
    next();  
});  
  
app.get('/', function(req, res) {  
    res.send("You have successfully accessed this server");  
});  
  
app.listen(3000);

Article Link:

https://alili.tech/en/archive/nodejs/express-set-cors-cross-origin/

# Latest Articles