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-2025

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

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


posted @   xgqfrms  阅读(98)  评论(13编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-04-30 js 文件上传 & 断点续传
2020-04-30 GSAP Animation All In One
2019-04-30 Apple & APPID & iOS & React Native
2019-04-30 Android Studio & zh-Hans
2019-04-30 React Native & Android & Text Input
2016-04-30 NMAP 使用教程 All In One
2016-04-30 SVG 1.1 (Second Edition) – 16 August 2011, text-rendering ,css禅意花园
点击右上角即可分享
微信分享提示