Expressjs 解决AJAX跨域请求 (CORS)
博客专区 > cyper 的博客 > 博客详情
Expressjs 解决AJAX跨域请求 (CORS)
cyper 发表于2年前
Expressjs 解决AJAX跨域请求 (CORS)
  • 发表于 2年前
  • 阅读 156
  • 收藏 2
  • 点赞 0
  • 评论 0

【腾讯云】买域名送云解析+SSL证书+建站!>>>   

摘要: 简单的REST service碰到了CORS问题,以下是我的解决过程。

在我的前端项目http://localhost:63342/replay.moqi.mobi/index.html
中访问expressjs的项目http://localhost:3000/blogs会出现跨域请求的问题,如下:

XMLHttpRequest cannot load http://localhost:3000/blogs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.

关于CORS,<pro express.js>书中38页介绍如下:

If you’re building an application (a REST API server) that serves requests coming from front-end clients hosted on different domains, you might encounter cross-domain limitations when making XHR/AJAX calls. In other words, browser requests are limited to the same domain (and port). The workaround is to use cross-origin resource sharing (CORS) headers on the server. If you don’t want to apply CORS headers to your server, then the JavaScript object literal notation with prefix (JSONP) is the way to go. Express.js has a res.jsonp() method that makes using JSONP a breeze. 
■ Tip to find out more about CorS, go to http://en.wikipedia.org/wiki/Cross-origin_resource_sharing.

####简单粗暴的办法是在res中加上两个header项,如下:

/* GET blog listing. */
router.get('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.json(blogs);

});

使用curl -i http://localhost:3000/blogs测试没有问题。在前端中使用requirejs-json插件访问也没有问题: 

define(['jquery', 'underscore', 'mustache', 'text!templates/nav.html', 'json!http://localhost:3000/blogs'],
    function ($, _, Mustache, navTemplate, blogPosts) {


###相关代码: 
后端的变化:https://github.com/uniquejava/moqi.mobi.express/commit/047cf53795a84a72d37fe0824d76273b17f8d7a5
前端的变化:https://github.com/uniquejava/replay.moqi.mobi/commit/7fd313a43d9d67d90df71450efd25a3149885610

####其它: 加一个middleware

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  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
});

### 使用connect-cors (最终选择了这个)

详见https://github.com/expressjs/cors的 Usage部分

1. 安装依赖

$ npm install cors

2. 对所有的路由启用cors

var express = require('express')
  , cors = require('cors')
  , app = express();

app.use(cors());

app.get('/products/:id', function(req, res, next){
  res.json({msg: 'This is CORS-enabled for all origins!'});
});

app.listen(80, function(){
  console.log('CORS-enabled web server listening on port 80');
});

3. 对某个路由启用cors

var express = require('express')
  , cors = require('cors')
  , app = express();

app.get('/products/:id', cors(), function(req, res, next){
  res.json({msg: 'This is CORS-enabled for all origins!'});
});

app.listen(80, function(){
  console.log('CORS-enabled web server listening on port 80');
});

4. 更多请看Usage...

 

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
cyper
粉丝 56
博文 619
码字总数 143128
×
cyper
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: