nodeJs 解决跨域

1. 使用 cors 中间件

cors 是一个 Node.js 的中间件,用于处理跨域请求。首先,需要通过 npm 安装 cors 包:

bash 复制代码
npm install cors

在 nodeJS 使用它

javascript 复制代码
const express = require("express");

const cors = require("cors");



const app = express();



// 全局使用 cors 中间件,允许所有来源的跨域请求

app.use(cors());



app.listen(3000, () => {

  console.log("服务器运行在 3000 端口");

});

如果只想允许特定来源的跨域请求,可以像这样配置:

javascript 复制代码
const corsOptions = {

  origin: "http://example.com", // 只允许来自 http://example.com 的请求

  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",

  allowedHeaders: "Content-Type,Authorization",

};



app.use(cors(corsOptions));

2. 设置响应头

也可以手动设置响应头来解决跨域问题。

javascript 复制代码
const express = require("express");



const app = express();



app.use((req, res, next) => {

  res.header("Access-Control-Allow-Origin", "*"); // 允许任何来源的请求

  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 允许的请求方法

  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization"); // 允许的请求头



  if (req.method === "OPTIONS") {

    res.sendStatus(200); // 对预检请求返回 200 状态码

  } else {

    next();

  }

});



app.listen(3000, () => {

  console.log("服务器运行在 3000 端口");

});
相关推荐
倾颜13 小时前
NestJS 核心概念梳理:从 Module、Controller 到 Guard、Interceptor
后端·node.js·nestjs
苦夏木禾20 小时前
tree-fs 批量创建文件
node.js
__zRainy__21 小时前
Node系列 · 数据库:单表查询
数据库·后端·mysql·node.js
薛定谔的算法1 天前
NestJS:让 Node.js 后端告别「野路子」
后端·node.js·nestjs
zzx2006__1 天前
node.js
node.js
念何架构之路1 天前
Gin中间件机制
中间件·gin
GitLqr2 天前
2026 Bun 全新姿态:从 Zig 到 Rust 的“暴力”重构与生态大爆发
rust·node.js·bun
Broccoli523026652 天前
FastAPI 中间件
中间件·fastapi
阿萨德528号2 天前
npm 包发布实战指南:从零发布、更新迭代到版本治理
前端·npm·策略模式
紫水木鱼3 天前
物联网通讯协议_MQTT_持续更新
物联网·中间件