Nodejs + 自定义 CORS
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习文章相关编程知识。下面本篇文章就来带大家聊聊《Nodejs + 自定义 CORS》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!
cors(跨源资源共享) 是一种允许一个域上的 web 应用程序访问另一个域上的资源的机制。当开发前端和后端分离并通过 api 进行通信的应用程序时,这一点至关重要。
这里有一篇文章解释了在 node.js 和 express 中不使用外部库的 cors 实现:
"use strict"; /*jshint node:true */ var simplemethods, simplerequestheaders, simpleresponseheaders, tolowercase, checkoriginmatch, origin; object.defineproperty(exports, "simplemethods", { get: function () { return [ "get", "head", "post", "put", "delete" ]; } }); simplemethods = exports.simplemethods; object.defineproperty(exports, "origin", { get: function () { return ["http://localhost:3000"]; } }); origin = exports.origin;
export simplemethods:定义 cors 请求允许的 http 方法(例如 get、post、put 等)。
导出来源:指定允许访问的来源列表。在此示例中,允许使用 http://localhost:3000。
object.defineproperty(exports, "simplerequestheaders", { get: function () { return ["accept", "accept-language", "content-language", "content-type", "authorization", "token"]; } }); simplerequestheaders = exports.simplerequestheaders; object.defineproperty(exports, "simpleresponseheaders", { get: function () { return ["cache-control", "content-language", "content-type", "expires", "last-modified", "pragma"]; } }); simpleresponseheaders = exports.simpleresponseheaders;
导出 simplerequestheaders:定义跨域请求中客户端允许的请求标头。
导出 simpleresponseheaders:定义从服务器到客户端允许的响应标头。
checkoriginmatch = function (originheader, origins, callback) { if (typeof origins === "function") { origins(originheader, function (err, allow) { callback(err, allow); }); } else if (origins.length > 0) { callback(null, origins.some(function (origin) { return origin === originheader; })); } else { callback(null, true); } };
函数 checkoriginmatch:检查请求来源是否与允许的来源列表匹配。如果匹配,则允许请求。
exports.create = function (options) { options = options || {}; options.origins = options.origins || origin; options.methods = options.methods || simplemethods;
来源和方法选项的初始化,如果未提供,则使用来自 origin 和 simplemethods 的默认值。
设置请求和响应标头
if (options.hasownproperty("requestheaders") === true) { options.requestheaders = tolowercase(options.requestheaders); } else { options.requestheaders = simplerequestheaders; } if (options.hasownproperty("responseheaders") === true) { options.responseheaders = tolowercase(options.responseheaders); } else { options.responseheaders = simpleresponseheaders; }
设置允许的请求(requestheaders)和响应(responseheaders)标头。将任何给定的请求或响应标头转换为小写。
附加中间件配置
options.maxage = options.maxage || null; options.supportscredentials = options.supportscredentials || false; if (options.hasownproperty("endpreflightrequests") === false) { options.endpreflightrequests = true; }
maxage:指定 cors 预检的最大缓存期限。 supportcredentials:确定服务器是否支持跨域请求中的凭据(cookie 或令牌)。 endpreflightrequests:决定服务器是否应终止预检请求(选项)或继续执行下一个中间件。
return function (req, res, next) { if (!req.headers.hasownproperty("origin")) { next(); } else { checkoriginmatch(req.headers.origin, options.origins, function (err, originmatches) { if (err !== null) { next(err); } else { var endpreflight = function () { if (options.endpreflightrequests === true) { res.writehead(204); res.end(); } else { next(); } };
函数 endpreflight:如果 endpreflightrequests 设置为 true,则结束预检(options)请求。来源检查:使用 checkoriginmatch 来验证请求来源是否与允许的来源匹配。
处理预检请求(选项)
if (req.method === "options") { if (!req.headers.hasownproperty("access-control-request-method")) { endpreflight(); } else { requestmethod = req.headers["access-control-request-method"]; if (req.headers.hasownproperty("access-control-request-headers")) { requestheaders = tolowercase(req.headers["access-control-request-headers"].split(/,\s*/)); } else { requestheaders = []; } methodmatches = options.methods.indexof(requestmethod) !== -1; if (!methodmatches) { endpreflight(); } else { headersmatch = requestheaders.every(function (requestheader) { return options.requestheaders.includes(requestheader); }); if (!headersmatch) { endpreflight(); } else { if (options.supportscredentials) { res.setheader("access-control-allow-origin", req.headers.origin); res.setheader("access-control-allow-credentials", "true"); } else { res.setheader("access-control-allow-origin", "*"); } if (options.maxage !== null) { res.setheader("access-control-max-age", options.maxage); } res.setheader("access-control-allow-methods", options.methods.join(",")); res.setheader("access-control-allow-headers", options.requestheaders.join(",")); endpreflight(); } } } }
请求方法和标头匹配:检查请求方法和标头是否与允许的匹配。 cors 响应标头:设置 cors 标头,例如 access-control-allow-origin、access-control-allow-credentials、access-control-allow-methods 等
在响应中公开标头
} 其他 {
if (options.supportscredentials) {
res.setheader("access-control-allow-origin", req.headers.origin);
res.setheader("access-control-allow-credentials", "true");
} 其他 {
res.setheader("access-control-allow-origin", "*");
}
exposedheaders = options.responseheaders.filter(function (header) { return !simpleresponseheaders.includes(header); }); if (exposedheaders.length > 0) { res.setheader("access-control-expose-headers", exposedheaders.join(",")); } next(); } } }); } };
} else { if (options.supportsCredentials) { res.setHeader("Access-Control-Allow-Origin", req.headers.origin); res.setHeader("Access-Control-Allow-Credentials", "true"); } else { res.setHeader("Access-Control-Allow-Origin", "*"); } exposedHeaders = options.responseHeaders.filter(function (header) { return !simpleResponseHeaders.includes(header); }); if (exposedHeaders.length > 0) { res.setHeader("Access-Control-Expose-Headers", exposedHeaders.join(",")); } next(); } } }); } };
access-control-expose-headers:如果 simpleresponseheaders 中未包含自定义标头,则设置客户端可访问的响应标头。
这就是如何在 node.js 中实现自定义 cors,而无需使用任何库。完整的脚本可以参考这个例子
本篇关于《Nodejs + 自定义 CORS》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

- 上一篇
- 使用 GitLab CI/CD 和 Terraform 实现 Lambda 以进行 SFTP 集成、Go 中的 S Databricks

- 下一篇
- 如何在 Nuxt 3 中使用 Redis 数据构建用户身份验证?
-
- 文章 · 前端 | 13分钟前 |
- HTML表单多行文本框高度自动调整技巧分享
- 126浏览 收藏
-
- 文章 · 前端 | 19分钟前 | JavaScript xml XMLHttpRequest DOMParser
- JS解析XML数据?4种主流方法全掌握!
- 132浏览 收藏
-
- 文章 · 前端 | 29分钟前 | 图片压缩 CanvasAPI 压缩质量 WebAssembly 客户端优化
- JS怎么压缩图片?手把手教你搞定客户端图片优化
- 105浏览 收藏
-
- 文章 · 前端 | 35分钟前 |
- HTML+CSShover效果怎么用?3大悬停案例教你搞定特效
- 165浏览 收藏
-
- 文章 · 前端 | 36分钟前 | 错误处理 权限管理 编码问题 串口通信 WebSerialAPI
- 手把手教你用JS搞定WebSerialAPI串口通信(5步轻松上手)
- 455浏览 收藏
-
- 文章 · 前端 | 48分钟前 |
- 前端必看!CSS单位全解析:这些常用单位你都用过吗?
- 193浏览 收藏
-
- 文章 · 前端 | 49分钟前 |
- 手把手教你用Vue.js打造旅游网站,实现超酷页面布局与交互
- 109浏览 收藏
-
- 文章 · 前端 | 50分钟前 |
- CSS必看!display:none和visibility:hidden的区别,搞懂这两个属性就对了!
- 119浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 茅茅虫AIGC检测
- 茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
- 93次使用
-
- 赛林匹克平台(Challympics)
- 探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
- 100次使用
-
- 笔格AIPPT
- SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
- 105次使用
-
- 稿定PPT
- 告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
- 99次使用
-
- Suno苏诺中文版
- 探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
- 98次使用
-
- 优化用户界面体验的秘密武器:CSS开发项目经验大揭秘
- 2023-11-03 501浏览
-
- 使用微信小程序实现图片轮播特效
- 2023-11-21 501浏览
-
- 解析sessionStorage的存储能力与限制
- 2024-01-11 501浏览
-
- 探索冒泡活动对于团队合作的推动力
- 2024-01-13 501浏览
-
- UI设计中为何选择绝对定位的智慧之道
- 2024-02-03 501浏览