expressjs路由和Nodejs服务器端发送REST请求
Nodejs创建自己的server后,我们如果需要从客户端利用ajax调用别的服务器端的数据API的接口,这时候出现了ajax跨域问题。一种是利用在客户端解决跨域问题
这种方案大家可以去网上查查
另一种方案是在服务器端去请求别的服务器,然后将数据再返回客户端.这里就涉及到了:
ajax请求,expressjs接收请求,Nodejs发送REST请求。
我着重写写关于这个方案的解决方法:
首先利用express创建路由,接收客户端发送的不同请求。
express路由可以接收get请求和post请求。
get请求可以去看API,因为平时我们可能对JSON的处理较多,所以用到POST请求较多,我这里主要写写post请求。
客户端发送请求:
客户端代码:
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/internaltool/project/peoples',
data: null,
async: false,
dataType: 'json',
success:function (data){
result = data;
},
error: function () {
alert("Save error!");
}
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url:'/internaltool/project/peopleInfoById',
data: '{"id": "811435467"}',
async: false,
dataType: 'json',
success:function (data){
},
error: function () {
alert("Save error!");
}
});
Nodejs接收客户端发送的请求,并且Nodejs服务器端发送REST请求别的服务器端取得数据。
Nodejs服务器端的代码:
var express = require('express'),
sr = require('./static_require'),
app = express.createServer();
// linql 2012/08/13 Add
app.configure(function(){
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
});
// End
var http = require('http');
exports.init = function(here) {
app.get('/*.js', sr.getHandler({
searchPaths:
}));
app.get('/*', function(req, res) {
res.sendfile(req.param(0))
});
// linql 2012/08/13 Add
// 这种情况是普通请求,不带有json数据处理
app.post('/internaltool/project/peoples', function(req, res) {
// the post options
var optionspost = {
host : '192.168.1.1',
port : '8080',
path : '/managesystem/Project/personList',
method : 'POST'
};
// do the POST call
// 服务器端发送REST请求
var reqPost = http.request(optionspost, function(resPost) {
resPost.on('data', function(d) {
res.send(d);
});
});
reqPost.end();
reqPost.on('error', function(e) {
console.error(e);
});
});
app.post('/internaltool/project/peopleInfoById', function(req, res) {
// Request of JSON data
// 接收客户端的JSON数据
var reqJosnData = JSON.stringify(req.body);
// do a POST request
// prepare the header
var postheaders = {
'Content-Type' : 'application/json; charset=UTF-8',
'Content-Length' : Buffer.byteLength(reqJosnData, 'utf8')
};
// the post options
var optionspost = {
host : '192.168.1.1',
port : '8080',
path : '/managesystem/Project/personMessageById',
method : 'POST',
headers : postheaders
};
// do the POST call
var reqPost = http.request(optionspost, function(resPost) {
resPost.on('data', function(d) {
res.send(d);
});
});
// write the json data
// 发送REST请求时传入JSON数据
reqPost.write(reqJosnData);
reqPost.end();
reqPost.on('error', function(e) {
console.error(e);
});
});
// End
};
关于expres.js可以参照:
http://www.csser.com/board/4f77e6f996ca600f78000936
Nodejs发送REST请求可以参照:
http://isolasoftware.it/2012/05/28/call-rest-api-with-node-js/
页:
[1]