xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Node.js & Express server support CORS

Node.js & Express server support CORS

express 开启 CORS

Express cors middleware

https://expressjs.com/en/resources/middleware/cors.html

https://www.npmjs.com/package/cors

https://github.com/expressjs/cors

// Simple Usage (Enable All CORS Requests)

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

// Enable CORS for a Single Route

var express = require('express')
var cors = require('cors')
var app = express()

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})
// Configuring CORS

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

// Configuring CORS w/ Dynamic Origin

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: function (origin, callback) {
    // db.loadOrigins is an example call to load
    // a list of origins from a backing database
    db.loadOrigins(function (error, origins) {
      callback(error, origins)
    })
  }
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

demo

server.js

/**
* express static server for react build/dist test!
*/

// simple express server for HTML pages!
// ES6 style

const cors = require('cors');
const express = require('express');
// const bodyParser = require('body-parser');
const fs = require('fs');
// const hostname = '127.0.0.1';
// const hostname = 'localhost';
const hostname = '10.1.159.45';
const port = 3000;
const app = express();

// 开启 CORS
// app.use(cors());
app.use(cors({
  credentials: true,
  origin: '*',
  // origin: 'http://*.xgqfrms.xyz',
}));
// app.options('*', cors());


// Starting with release 4.16.0, a new express.json() middleware is available.
app.use(express.json());
app.use(express.urlencoded({
  extended: true,
}));

app.use(express.static(__dirname + '/public'));

app.set('views', './views');
// app.set('view engine', 'pug');


app.use(function (req, res, next) {
  // JSON parse
  // console.log('req.body', req.body);
  res.header("Access-Control-Allow-Origin", "*");
  // logger
  // // 获取主机名和IP地址
  // console.log('\nreq.ip =', req.ip);
  // console.log('req.hostname =', req.hostname);
  // // 获取原始请求URL
  // console.log('req.originalUrl =', req.originalUrl);
  next();
});

client.js


fetch(`http://10.1.159.45:3000/api/post`, {
// fetch(`http://localhost:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    // cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST",
    // cookies
    // credentials: 'include',
    mode: "no-cors",
    // mode: "cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));
// Promise {<pending>}
// res = Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}



fetch(`http://10.1.159.45:3000/api/post`, {
// fetch(`http://localhost:3000/api/post`, {
    body: JSON.stringify({key: "value"}),
    // cache: "no-cache",
    headers: {
        "Content-Type": "application/json",
    },
    method: "POST",
    // cookies
    // credentials: 'include',
    // mode: "no-cors",
    mode: "cors",
})
.then(res => console.log(`res =`, res))
.catch(err => console.error(`error =`, err));
// Promise {<pending>}
//  res = Response {type: "cors", url: "http://10.1.159.45:3000/api/post", redirected: false, status: 200, ok: true, …}

refs



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-04-30 15:39  xgqfrms  阅读(92)  评论(13编辑  收藏  举报