使用 Node.js 内置 http 模块的createServer()方法创建一个新的HTTP服务器并返回json数据,代码如下:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const data = [
{ name: '测试1号', index: 0 },
{ name: '测试2号', index: 1 },
{ name: '测试3号', index: 2 },
];
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
const path = url.split('?')[0];
// 允许跨域
res.setHeader("Access-Control-Allow-Origin", "*");
if (path === '/api/list' && method === 'GET') {
try {
res.writeHead(200, 'OK', {'Content-type': 'application/json'});
res.end(JSON.stringify(data));
} catch (error) {
res.writeHead(500, 'Bad', {'Content-type': 'application/json'});
res.end('server error');
}
} else {
// 没有定义的路由返回404
res.writeHead(404, {'ContentType': 'text/plain'});
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
要运行此代码段,请将其另存为 server.js 文件并在你的终端中运行 node server.js
接口地址是 http://127.0.0.1:3000/api/list