用nodejs实现json和jsonp服务

一、JSON和JSONP

JSONP的全称是JSON with Padding,由于同源策略的限制,XmlHttpRequest只允许请求当前源(协议,域名,端口)的资源。如果要进行跨域请求,我们可以通过使用html的script标记来进行跨域请求,并在相应中返回要执行的script代码,其中可以直接使用JSON传递javascript对象。这种跨域的通讯方式成为JSONP。

由此我们可以看出两者的区别:

json: 一种轻量级的数据格式。

jsonp:为实现跨域,而采用的一种脚本注入方法。

备注:要了解更多json,可以参见我原先写的一篇介绍json的文章:《JSON那些事》

二、实现

为了简单起见,我们要读取数据都是

jQuery111300015746519762624978_1477902649311

({"first_name":"888","last_name":"888"})

1. 服务器端代码:


var express = require('express');

var app = express();

app.use(express.static('public'));

app.get('/index.html', function (req, res) {

res.sendFile( __dirname + "/" + "index.html" );

})

app.get('/process_get', function (req, res) {

// 输出 JSON 格式

response =({

first_name:req.query.first_name,

last_name:req.query.last_name

});

res.end(req.query.callback+'('+JSON.stringify(response)+')');//jsonp格式

// res.end("("+JSON.stringify(response)+")");

})

var server = app.listen(8081, function () {

var host = server.address().address

var port = server.address().port

console.log("应用实例,访问地址为 http://%s:%s", host, port)

})

2. 游览器端代码,为方便起见,我直接用了jquery的方法

$.ajax({​

url: "http://127.0.0.1:8081/process_get?first_name=888&last_name=888",

dataType: "jsonp",

success: function (data) {

console.log(44444);

console.log(data);

},

error: function(XMLHttpRequest, textStatus, error) {

console.log(XMLHttpRequest.status);

console.log(XMLHttpRequest.readyState);

console.log(textStatus);

console.log(error);

},

})