nodejs 的express 接口内容相关问题记录

发布于:2024-04-17 ⋅ 阅读:(18) ⋅ 点赞:(0)

nodejs的 express 接口如何回复为html内容

代码如下

const express = require('express');
const app = express();

// Define a route to handle the HTML response
app.get('/html-response', (req, res) => {
  // Set the Content-Type to text/html
  res.setHeader('Content-Type', 'text/html');
  
  // Send the HTML content as the response
  res.send('<h1>Hello, this is HTML content!</h1>');
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

当接口请求的是application/json 的 post请求时 nodejs 的express 如何接收参数?

npm install express body-parser

 app.use(bodyParser.json());

const name = req.body.name;

node express 设置跨域资源共享 设置

npm install cors

const express = require('express');
const cors = require('cors');
const app = express();

const corsOptions = {

origin: '*',

methods: '*',

allowedHeaders: '*',

};

app.use(cors(corsOptions));

如何对express 返回的json 都套一层统一的模板 

创建一个中间件

// middleware function to wrap JSON responses
const wrapResponse = (req, res, next) => {
  // Save the original res.json() function
  const originalJson = res.json;

  // Create a new res.json() function
  res.json = function (data) {
    // Wrap the response data in the desired template
    const wrappedData = {
      status: 'success',
      data: data,
    };

    // Call the original res.json() function with the wrapped data
    originalJson.call(this, wrappedData);
  };

  // Move to the next middleware or route handler
  next();
};

module.exports = wrapResponse;

使用

// 统一对json返回加一层统一的状态码

const wrapResponse = require('./middleware/wrapResponse');

app.use(wrapResponse);