serve/api.js
var http = require('http');
var Server = http.createServer();
Server.on('request',function(request,response){
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
request.on('data',(buff)=>{
request.body = JSON.parse(buff.toString());
})
request.on('end', ()=>{
console.log(request.body)
//数据处理
switch(request.url){
case '/name': response.end(JSON.stringify({ code: 200, method: 'name', data: [] })); break;
case '/login': response.end(JSON.stringify({ code: 200, method: 'login', data: [] })); break;
case '/': response.end(JSON.stringify({code: 200}))
}
})
});
Server.listen('1000',function(){
console.log('服务已启动');
});
终端
>node serve/api.js
服务已启动
page/index.js
function request(api, params) {
return new Promise((resolve, reject)=>{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const res = JSON.parse(this.responseText)
resolve(res)
}
};
xhttp.open("post", `http://localhost:1000${api}`, true);
let data = JSON.stringify(params||{})
xhttp.send(data);
})
}
request('/name', {name: '小明'}).then(res=>{
console.log(res)
})
node每次修改后都要重启
可全局下载nodemon
npm install nodemon- g
使用时:
nodemon api.js
网友评论