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

在Node.js(Express.js)中能否为JSON数据应用CSS样式?

解决方法:给Express返回的书籍数据添加样式

你现在直接用res.json(books)返回JSON的话,没法用CSS直接样式化——因为JSON是纯数据格式,浏览器只会用默认的单调视图展示它。要实现样式化,得换几种方式来做:

方法1:把JSON转成HTML再返回,直接嵌入CSS

修改你的路由处理逻辑,把书籍数据转换成带HTML结构的内容,同时加入CSS样式:

const express = require('express')
const app = express()
const port = 5000
const books = require('./book-list')

app.get('/', (req,res)=>{
  // 生成带样式的HTML
  const htmlContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <style>
        .book-container {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
          gap: 20px;
          padding: 20px;
        }
        .book-card {
          border: 1px solid #ddd;
          border-radius: 8px;
          padding: 15px;
          box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .book-title {
          font-size: 1.2rem;
          font-weight: bold;
          color: #2c3e50;
          margin: 0 0 10px;
        }
        .book-author {
          color: #7f8c8d;
          margin: 5px 0;
        }
      </style>
    </head>
    <body>
      <h1>书籍列表</h1>
      <div class="book-container">
        ${books.map(book => `
          <div class="book-card">
            <h3 class="book-title">${book.title || '无标题'}</h3>
            <p class="book-author">作者:${book.author || '未知'}</p>
            <p>出版年份:${book.year || '未知'}</p>
          </div>
        `).join('')}
      </div>
    </body>
    </html>
  `
  res.status(200).send(htmlContent)
})

app.listen(port,()=>{
  console.log(`Server is listening on localhost:${port}`)
})

方法2:用中间件美化JSON的默认显示

如果只是想让JSON的排版更美观(不是自定义CSS样式),可以用Express中间件来格式化JSON输出:

  1. 安装中间件(比如express-prettify):
npm install express-prettify
  1. 修改代码使用中间件:
const express = require('express')
const app = express()
const port = 5000
const books = require('./book-list')
const prettify = require('express-prettify')

// 启用美化中间件
app.use(prettify({ query: 'pretty' }))

app.get('/', (req,res)=>{
  // 访问时加?pretty参数就能看到美化后的JSON
  res.status(200).json(books)
})

app.listen(port,()=>{
  console.log(`Server is listening on localhost:${port}`)
})

访问http://localhost:5000/?pretty就能看到排版整齐的JSON了。

方法3:前端分离渲染(推荐)

把Express作为纯API服务,前端单独写HTML/CSS/JS来请求数据并样式化:

  1. 先修改Express代码,专门提供API:
const express = require('express')
const app = express()
const port = 5000
const books = require('./book-list')

// 允许跨域(如果前端和后端端口不同)
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  next()
})

app.get('/api/books', (req,res)=>{
  res.status(200).json(books)
})

app.listen(port,()=>{
  console.log(`Server is listening on localhost:${port}`)
})
  1. 新建一个前端HTML文件(比如index.html):
<!DOCTYPE html>
<html>
<head>
  <style>
    /* 这里写你需要的样式,和方法1的CSS类似 */
    .book-list {
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
    }
    .book-item {
      border-bottom: 1px solid #eee;
      padding: 15px 0;
    }
    .book-item h2 {
      margin: 0 0 5px;
      color: #3498db;
    }
  </style>
</head>
<body>
  <div class="book-list" id="bookList"></div>

  <script>
    // 请求API获取书籍数据
    fetch('http://localhost:5000/api/books')
      .then(res => res.json())
      .then(books => {
        const bookList = document.getElementById('bookList')
        books.forEach(book => {
          const item = document.createElement('div')
          item.className = 'book-item'
          item.innerHTML = `
            <h2>${book.title}</h2>
            <p>作者:${book.author}</p>
            <p>ISBN:${book.isbn || '无'}</p>
          `
          bookList.appendChild(item)
        })
      })
  </script>
</body>
</html>

直接打开这个HTML文件,就能看到带样式的书籍列表了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:58:33