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 端口");

});
相关推荐
Vone_666 小时前
node.js 邮箱验证服务器搭建
运维·服务器·node.js
程序员拂雨8 小时前
HTTP和HTTPS模块
http·https·node.js
Cxzzzzzzzzzz10 小时前
Kafka Go客户端--Sarama
中间件·golang·kafka·linq
Paraverse_徐志斌12 小时前
Kafka 如何保证消息顺序性
分布式·中间件·kafka·消息队列
dgiij13 小时前
excel大表导入数据库
数据库·mysql·node.js·excel
x-cmd14 小时前
[250512] Node.js 24 发布:ClangCL 构建,升级 V8 引擎、集成 npm 11
前端·javascript·windows·npm·node.js
Johnstons1 天前
AnaTraf:深度解析网络性能分析(NPM)
前端·网络·安全·web安全·npm·网络流量监控·网络流量分析
martian6651 天前
信创生态核心技术栈:数据库与中间件
开发语言·中间件·系统架构·系统安全·创业创新
极小狐1 天前
极狐GitLab 容器镜像仓库功能介绍
java·前端·数据库·npm·gitlab
神奇侠20242 天前
快速开发-基于gin的中间件web项目开发
中间件·gin