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

Node.js:如何在Jade模板中展示外部网站POST的JSON数据

解决Node+Jade渲染POST过来的Movie JSON数据问题

嘿,别慌!花了6小时没头绪确实闹心,咱们一步步把这个问题拆解解决~

首先,你已经完成了前端POST数据到Node服务器的第一步,接下来需要搞定Node端接收数据和Jade模板渲染数据这两个核心环节,下面是具体步骤:

1. 配置Node服务器接收POST的JSON数据

假设你用的是Express框架(Node开发最常用的),首先得确保安装了必要的依赖,然后配置中间件解析JSON请求体:

安装依赖

打开终端运行:

npm install express body-parser --save

编写Node服务器代码

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 8080;

// 关键:解析前端发来的JSON格式请求体
app.use(bodyParser.json());

// 设置Jade为模板引擎,指定模板文件目录(默认是项目下的views文件夹)
app.set('view engine', 'jade');
app.set('views', './views');

// 处理你的POST请求
app.post('/', (req, res) => {
  // 这里就能拿到前端传过来的movie JSON数据啦
  const movie = req.body;
  // 把数据传给Jade模板,渲染页面返回给前端
  res.render('movie', { movie });
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器跑在 http://localhost:${port} 啦`);
});

2. 编写Jade模板渲染数据

在项目根目录下新建views文件夹,然后在里面创建movie.jade文件,用Jade的语法展示你的movie数据:

html
  head
    title= movie.title
  body
    div(class="movie-card")
      h1= movie.title
      p 种子编号:#{movie.seed}
      a(href=movie.url, target="_blank") 打开影片链接

这里用了两种插入变量的方式:=直接输出变量内容,#{}在文本中插入变量,按需使用就行。

3. 修复前端POST请求的小问题

你之前的前端代码可能漏了关键的请求头设置,导致Node端无法正确解析JSON,补充一下:

var http = new XMLHttpRequest();
var url = "http://localhost:8080/";
// 假设arr是你的movie对象,比如 {title: "星际穿越", seed: 1001, url: "xxx.com"}
var params = arr;

http.open('POST', url, true);
// 必须加这个!告诉服务器我们发的是JSON格式
http.setRequestHeader('Content-Type', 'application/json');

// 请求成功后的处理
http.onload = function() {
  if (this.status >= 200 && this.status < 400) {
    // 把服务器返回的渲染好的页面插入到当前页面
    document.body.innerHTML = this.responseText;
  } else {
    console.log('请求出错啦');
  }
};

// 发送请求前要把JSON对象转成字符串
http.send(JSON.stringify(params));

额外提示:如果是多个movie数据

如果你的arr是包含多个movie对象的数组,那Node端要改成接收数组,Jade里用循环渲染:

  • Node端修改:
    app.post('/', (req, res) => {
      const movies = req.body;
      res.render('movies', { movies });
    });
    
  • 对应的movies.jade模板:
    html
      head
        title 影片列表
      body
        h1 我的影片收藏
        each movie in movies
          div(class="movie-card")
            h2= movie.title
            p 种子编号:#{movie.seed}
            a(href=movie.url, target="_blank") 打开链接
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:44:56