环境node 官网下载
node代码 get请求写接口以及返回数据 post 数据存储在body中 本文只是用get因为关于使用的是jsonp只支持get
var http= require(‘http‘);
var fs= require(‘fs‘);
var url = require(‘url‘);
var querystring = require(‘querystring‘)
var server= http.createServer(function(req, res){
if(req.method === "GET"){
var pathname = url.parse(req.url).pathname
//截取?后面的内容
var info = querystring.parse(req.url)
console.log(pathname)
console.log(info)
// 设置返回数据的Content-type为JSON
res.setHeader(‘Content-type‘, ‘application/json‘)
let resData = {
error: 0,
message: ‘GET返回成功‘,
data: {
query: info.ceshi
}
}
res.end("cb("+JSON.stringify(resData)+")");
}
if(req.method === "POST"){
// 定义了一个post变量,用于暂存请求体的信息
var post = ‘‘;
// 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
req.on(‘data‘, function(chunk){
post += chunk;
});
// 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回。
req.on(‘end‘, function(){
post = querystring.parse(post);
console.log(post)
res.end("cb("+JSON.stringify(resData)+")");
});
}
});
server.listen(5000);
console.log("server is running at http://127.0.0.1:5000");
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="jquery.min.js"></script>
</head>
<body>
<div>
<h1>node 测试</h1>
</div>
</body>
<script>
$.ajax({
url: "http://127.0.0.1:5000/",
type: "get",
data: {
"ceshi":"测试数据",
},
dataType: "jsonp", //指定服务器返回的数据类型
jsonpCallback: "cb", //指定回调函数名称
success: function (res) {
console.log(res)
}
});
</script>
</html>
原文:https://www.cnblogs.com/wuyexuetu/p/12888888.html