首次接触node 将自己的模拟接口的整个过程记录下来:
1)我想要通过接口调用一些学生的信息,首先创建stuInfo.json文件,长这样:
{
"stu" : [{
"name": "赵帙",
"age": 10,
"weight": 36,
"grade": "小学",
"classes": "三班"
},{
"name": "林溪",
"age": 14,
"weight": 43,
"grade": "初中",
"classes": "二班"
},{
"name": "季忱",
"age": 17,
"weight": 47,
"grade": "高中",
"classes": "一班"
}]
}
2)在项目的跟目录下新建一个getStuInfo.js的文件 模拟接口。在终端中进入项目所在文件,运行node getStuInfo.js在浏览器中访问http://localhost:8686/api就可以看到stuInfo.json的数据。
const http = require('http');
const fs = require("fs");
const port = 8686;
let server = http.createServer((req, res) => {
console.log('req:', req.url, req.method);
res.setHeader('Content-Type','application/json;charset=utf8');
res.setHeader('Access-Control-Allow-Origin','*'); //跨域处理
if(req.url.startsWith('/api') && req.method === 'GET') {
let reqStr = '';
req.on('data', (chunk) => reqStr += chunk);
req.on('end', () => {
let resData = fs.readFileSync('./stuInfo.json');
res.end(resData)
});
return void 0;
}else{
console.log('其他请求')
}
});
server.listen(port, () => {
console.log(`Node.js已经监听了${port}端口`);
})
3)调用接口时:
axios.get('//localhost:8686/api')
.then((res) => {
console.log(JSON.parse(res.request.responseText).stu) //接口返回的数据
})
.catch((err) => {
console.log(err);
})