node res.end返回json格式数据

本文介绍了如何使用Node.js的内置http模块创建一个HTTP服务器,处理GET请求返回JSON数据,并实现跨域功能。示例代码展示了如何在`/api/list`路径上提供一个API接口。
摘要由CSDN通过智能技术生成

使用 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
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值