0

0

Nodejs + 自定义 CORS

心靈之曲

心靈之曲

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

|

1040人浏览过

|

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

设置请求和响应标头

Huemint
Huemint

推荐!用AI自定义和谐配色

下载
 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工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

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

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

178

2024.05.11

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

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

217

2025.12.18

if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

779

2023.08.22

cookie
cookie

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

6428

2023.06.30

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

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

347

2023.11.23

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

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

414

2024.02.23

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

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

93

2025.08.19

js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

515

2023.06.20

C++ 设计模式与软件架构
C++ 设计模式与软件架构

本专题深入讲解 C++ 中的常见设计模式与架构优化,包括单例模式、工厂模式、观察者模式、策略模式、命令模式等,结合实际案例展示如何在 C++ 项目中应用这些模式提升代码可维护性与扩展性。通过案例分析,帮助开发者掌握 如何运用设计模式构建高质量的软件架构,提升系统的灵活性与可扩展性。

8

2026.01.30

热门下载

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

精品课程

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

共83课时 | 8.4万人学习

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

共15课时 | 4.5万人学习

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

共28课时 | 5.3万人学习

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

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号