【nodejs】服务器处理url请求并返回json数据

本文介绍如何使用Node.js建立一个服务器,监听特定URL并返回JSON数据。客户端通过AJAX请求该URL,但遇到了jQuery.ajax()的SyntaxError。在服务器端,我们展示了如何将对象数组转换为JSON字符串并发送给客户端。

参考:http://stackoverflow.com/questions/5892569/responding-with-a-json-object-in-nodejs-converting-object-array-to-json-string


客户端用ajax获取url返回的json,具体问题见【error】jQuery.ajax()报错Uncaught SyntaxError: Unexpected token

服务器用nodejs写,创建一个服务器监听具体url并用回调函数处理,返回json数据。(nodejs基础见【nodejs】imooc上的学习笔记


代码示例:

客户端html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>addon</title>
	<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
</head>
<body>
	<div>
		<button>click me!</button>		
		<p>...</p>
	</div>

	<script type="text/javascript">
	const hostname = '127.0.0.1';
	const port = 1337;
	$(function(){
		$("button").bind("click",function(){
			var url = "http://" + hostname + ":" + port;
			$.ajax({
				url:url,
				dataType:"jsonp",
				jsonp:"callback",
				jsonpCallback:"success_jsonpCallback"
			}).done(function(data) {
				$("p").html(data.toString);
			});
		});
	});
	</script>
</body>
</html>


nodejs服务器:

const http = require('http');
const addon = require('./build/Release/addon');//调c++方法引入的

const hostname = '127.0.0.1';
const port = 1337;

http.createServer((req, res) => {
  res.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  var json = JSON.stringify({ 
    anObject: otherObject, 
    anArray: otherArray, 
    another: addon.hello()<span style="white-space:pre">	</span>//c++文件中暴露的方法
  });
  res.end("success_jsonpCallback(" + json + ")");<span style="white-space:pre">	</span>//!!一定要加配置的回调方法名
  // res.writeHead(200, { 'Content-Type': 'text/plain' });
  // res.end(addon.hello());
}).listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});


记得先起服务器,在按网页上的按钮。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值