nodejs如何跨域请求

http.request(options, callback) options是构建请求的必要参数 callback是请求成功后执行的回调函数 是没有域的限制的。

可以使用POST的方式传递数据req.write()就是向POST请求中写入传递的参数。

req.write()的确是传递的参数,但是光写上这个是不够的,必须在options中加上 headers:{'Content-Type':'application/json','Content-Length': data.length} 如果数据是 querystring 格式则 'Content-Type':'application/x-www-form-urlencoded'

参见:http://nodejs.org/api/http.html#http_http_request_options_callback

 

Node.js express 跨域问题

 

跨域问题主要在header上下功夫 首先提供一个w3c的header定义 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 再提供一个网友提供的header详解 http://kb.cnblogs.com/page/92320/ 这两个有助于帮助大家理解header的类型和作用, 但是遗憾的是跨域相关的两个header属性我都没有找到相关的定义, 下面直接告诉大家 1是Access-Control-Allow-Origin 允许的域 2是Access-Control-Allow-Headers 允许的header类型

第一项可以直接设为* 表示任意 但是第二项不能这样写,在chrome中测试跨域发现报错, 最终的代码看起来是这个样子:

app.all('', function(req, res, next) { res.header("Access-Control-Allow-Origin", ""); res.header("Access-Control-Allow-Headers", “Content-Type,Content-Length, Authorization, Accept,X-Requested-With”); res.header(“Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS”); res.header(“X-Powered-By",’ 3.2.1’) if(req.method=="OPTIONS”) res.send(200);/让options请求快速返回/ else next(); });

[原]解决NodeJS+Express模块的跨域访问控制问题:Access-Control-Allow-Origin

在一个项目上想用NodeJS,在前端的JS(http://localhost/xxx)中ajax访问后端RestAPI(http://localhost:3000/….)时(Chrome)报错:

XMLHttpRequest cannot load http://localhost:3000/auth/xxx/xxx. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

解决代码:

方案一:
var express = require('express');
var app = express();
//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.get('/auth/:id/:password', function(req, res) {
    res.send({id:req.params.id, name: req.params.password});
});

app.listen(3000);
console.log('Listening on port 3000...');
方案二:
var express = require('express');
var app = express();

app.get('/auth/:id/:password', function(req, res) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    res.send({id:req.params.id, name: req.params.password});
});

app.listen(3000);
console.log('Listening on port 3000...');
posted @ 2015-06-04 15:58  徐学进  阅读(488)  评论(0)    收藏  举报