You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS/Express中对应PHP file_get_contents('php://input')的等效方法是什么?

Node.js(TypeScript)获取AJAX传入JSON的等效方法

对应PHP中file_get_contents('php://input')的功能,在Node.js(TypeScript)中不同场景有不同实现方式:

1. 原生Node.js(无框架)

手动监听请求的data和end事件,读取原始请求体后解析为JSON:

import * as http from 'http';

const server = http.createServer((req, res) => {
  // 仅处理POST类型的JSON请求
  if (req.method === 'POST' && req.headers['content-type']?.includes('application/json')) {
    let rawBody = '';

    // 接收请求数据块
    req.on('data', (chunk) => {
      rawBody += chunk.toString();
    });

    // 数据接收完成后解析JSON
    req.on('end', () => {
      try {
        const jsonData = JSON.parse(rawBody);
        console.log('解析后的JSON:', jsonData);
        
        // 处理业务逻辑后返回响应
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ code: 200, data: jsonData }));
      } catch (err) {
        // 处理JSON解析错误
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ code: 400, msg: '无效的JSON格式' }));
      }
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ code: 404, msg: '接口不存在' }));
  }
});

server.listen(3000, () => {
  console.log('服务运行在端口3000');
});

2. Express框架

Express提供内置的express.json()中间件,自动解析JSON请求体,直接通过req.body获取解析后的对象:

import express from 'express';
const app = express();

// 启用JSON解析中间件,替代手动读取原始请求体
app.use(express.json());

app.post('/api/your-endpoint', (req, res) => {
  // req.body即为解析后的JSON对象
  const jsonData = req.body;
  console.log('接收的JSON数据:', jsonData);
  
  res.json({ code: 200, data: jsonData });
});

app.listen(3000, () => {
  console.log('Express服务运行在端口3000');
});

3. Koa框架

Koa需要借助koa-bodyparser中间件实现JSON解析:
首先安装依赖:

npm install koa-bodyparser @types/koa-bodyparser

然后编写代码:

import Koa from 'koa';
import bodyParser from 'koa-bodyparser';

const app = new Koa();

// 使用bodyparser中间件解析JSON请求体
app.use(bodyParser());

app.use(async (ctx) => {
  if (ctx.method === 'POST') {
    // ctx.request.body是解析后的JSON对象
    const jsonData = ctx.request.body;
    console.log('接收的JSON数据:', jsonData);
    
    ctx.body = { code: 200, data: jsonData };
  } else {
    ctx.status = 404;
    ctx.body = { code: 404, msg: '接口不存在' };
  }
});

app.listen(3000, () => {
  console.log('Koa服务运行在端口3000');
});

内容的提问来源于stack exchange,提问作者user14692598

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:00:49