栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在node.js的express.js框架中启用跨域资源共享(CORS)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在node.js的express.js框架中启用跨域资源共享(CORS)

查看来自enable-cors.org的示例:

在node.js上的ExpressJS应用中,对路由执行以下操作:

app.all('/', function(req, res, next) {  res.header("Access-Control-Allow-Origin", "*");  res.header("Access-Control-Allow-Headers", "X-Requested-With");  next(); });app.get('/', function(req, res, next) {  // Handle the get for this route});app.post('/', function(req, res, next) { // Handle the post for this route});

首次呼叫(

app.all
)应该在应用中的所有其他路由(或至少要启用CORS的路由)之前进行。

[编辑]

如果您还希望显示静态文件的标头,请尝试执行此操作(确保在调用之前

use(express.static())

app.use(function(req, res, next) {  res.header("Access-Control-Allow-Origin", "*");  res.header("Access-Control-Allow-Headers", "X-Requested-With");  next();});

我用您的代码对此进行了测试,并从

public
目录中获取了资产的标头:

var express = require('express')  , app = express.createServer();app.configure(function () {    app.use(express.methodOverride());    app.use(express.bodyParser());    app.use(function(req, res, next) {      res.header("Access-Control-Allow-Origin", "*");      res.header("Access-Control-Allow-Headers", "X-Requested-With");      next();    });    app.use(app.router);});app.configure('development', function () {    app.use(express.static(__dirname + '/public'));    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));});app.configure('production', function () {    app.use(express.static(__dirname + '/public'));    app.use(express.errorHandler());});app.listen(8888);console.log('express running at http://localhost:%d', 8888);

当然,您可以将该功能打包到一个模块中,以便可以执行以下操作

// cors.jsmodule.exports = function() {  return function(req, res, next) {    res.header("Access-Control-Allow-Origin", "*");    res.header("Access-Control-Allow-Headers", "X-Requested-With");    next();  };}// server.jscors = require('./cors');app.use(cors());


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380397.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号