讲师中心 微信公众号
AI工具推荐 视频效率加速

Nodejs + 自定义 CORS

老涛君_7983

老涛君_7983

发布时间:2024-11-13 13:33:19

|

1100人浏览过

|

来源于dev.to

转载

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 的默认值。

设置请求和响应标头

Web Accessibility (WCAG 2 AA))
Web Accessibility (WCAG 2 AA))

将 WCAG 2 AA 无障碍标准应用于设计系统、UI 组件和网页——通过可运行的验证器进行对比度计算,采用设计 token 模式使颜色天生可访问,设定排版和焦点状态规则,并提供语义检查清单。适用于构建或审查 UI。

下载
 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,而无需使用任何库。完整的脚本可以参考这个例子

热门AI工具

更多
超级简历WonderCV

一款AI办公效率工具,主要用于免费求职简历模版下载制作,应届生职场人必备简历制作神器,适合需要提升相关任务效率的用户。

Atoms
Atoms Hot

Atoms是一款AI智能体工具,第一支自动构建真实业务的 AI 团队。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

UP简历
UP简历 Hot

一款AI办公效率工具,主要用于基于AI技术的免费在线简历制作工具,适合需要提升相关任务效率的用户。

SkildArt
SkildArt Hot

SkildArt是一款AI文本写作工具,一站式 AI 视觉创作平台。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

二狗PPT
二狗PPT Hot

一款AI演示文稿工具,主要用于专为中式职场打造的AI PPT生成工具,适合需要提升相关任务效率的用户。

讯飞智作

讯飞智作是一款AI视频创作工具,AI文本配音工具,数字人课程、营销视频制作。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

相关专题

更多
什么是中间件
什么是中间件

中间件是一种软件组件,充当不兼容组件之间的桥梁,提供额外服务,例如集成异构系统、提供常用服务、提高应用程序性能,以及简化应用程序开发。想了解更多中间件的相关内容,可以阅读本专题下面的文章。

689

2024.05.11

Golang 中间件开发与微服务架构
Golang 中间件开发与微服务架构

本专题系统讲解 Golang 在微服务架构中的中间件开发,包括日志处理、限流与熔断、认证与授权、服务监控、API 网关设计等常见中间件功能的实现。通过实战项目,帮助开发者理解如何使用 Go 编写高效、可扩展的中间件组件,并在微服务环境中进行灵活部署与管理。

644

2025.12.18

ThinkPHP中间件机制与请求拦截处理实践
ThinkPHP中间件机制与请求拦截处理实践

本专题围绕 ThinkPHP 中间件体系展开,深入讲解中间件的定义、注册与执行流程。内容包括全局中间件与路由中间件的区别、请求前后处理逻辑、自定义中间件开发以及权限验证与日志处理应用。通过实际案例,帮助开发者掌握中间件在项目中的核心作用与最佳实践。

458

2026.03.31

Node.js后端开发与Express框架实践
Node.js后端开发与Express框架实践

本专题针对初中级 Node.js 开发者,系统讲解如何使用 Express 框架搭建高性能后端服务。内容包括路由设计、中间件开发、数据库集成、API 安全与异常处理,以及 RESTful API 的设计与优化。通过实际项目演示,帮助开发者快速掌握 Node.js 后端开发流程。

781

2026.02.10

cookie
cookie

Cookie 是一种在用户计算机上存储小型文本文件的技术,用于在用户与网站进行交互时收集和存储有关用户的信息。当用户访问一个网站时,网站会将一个包含特定信息的 Cookie 文件发送到用户的浏览器,浏览器会将该 Cookie 存储在用户的计算机上。之后,当用户再次访问该网站时,浏览器会向服务器发送 Cookie,服务器可以根据 Cookie 中的信息来识别用户、跟踪用户行为等。

12439

2023.06.30

document.cookie获取不到怎么解决
document.cookie获取不到怎么解决

document.cookie获取不到的解决办法:1、浏览器的隐私设置;2、Same-origin policy;3、HTTPOnly Cookie;4、JavaScript代码错误;5、Cookie不存在或过期等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

1246

2023.11.23

阻止所有cookie什么意思
阻止所有cookie什么意思

阻止所有cookie意味着在浏览器中禁止接受和存储网站发送的cookie。阻止所有cookie可能会影响许多网站的使用体验,因为许多网站使用cookie来提供个性化服务、存储用户信息或跟踪用户行为。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

844

2024.02.23

cookie与session的区别
cookie与session的区别

本专题整合了cookie与session的区别和使用方法等相关内容,阅读专题下面的文章了解更详细的内容。

1946

2025.08.19

Uvicorn 报错与问题解决教程
Uvicorn 报错与问题解决教程

本专题汇总了Uvicorn服务器常见问题与报错解决的教程合集,涵盖启动失败、端口占用、模块导入错误、事件循环冲突及热重载失效等典型故障的排查思路。同时整理了多进程与Worker配置、SSL/HTTPS证书报错、跨域与代理配置等实战解决方案,助你快速定位并解决Uvicorn运行中的各类问题。

0

2026.11.02

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
快速入门Node.JS全套完整版
快速入门Node.JS全套完整版

共83课时 | 13.6万人学习

nodejs开发基础教程
nodejs开发基础教程

共15课时 | 4.9万人学习

JavaScript设计模式视频教程
JavaScript设计模式视频教程

共28课时 | 6.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn