Express Can‘t set headers after they are sent.问题

When I was learning node recently, when using Express, the backend server terminal encountered the problem Can't set headers after they are sent.

Problem Description

System: Windows 7 x64
Node.js version: The version is: v8.16.0
A piece of backend code that simulates HTTP requests has the following error: Error: Can't set headers after they are sent.
Translation: Can't set headers after they are sent.
The screenshot is as follows:
Insert image description here
At this time, my background server code is like this

/*
 * @Author: bkk
 * @weixin: biankuan1996
 * @email: [email protected]
 * @Date: 2021-06-17 11:06:12
 * @LastEditTime: 2021-06-17 11:55:47
 */
const express = require('express');
var app = express();

// 所有的请求
app.all("*",function (req,res,next) {
    
    
    // 相当于域名白名单,不能写 * ,因为 * 是通配符  所有网站都可以访问
    res.setHeader('Access-control-Allow-Origin','*')

    res.setHeader('Access-control-Allow-Headers','X-request-Width')
    // ...Headers必须的固定值
    res.setHeader('Access-control-Allow-Methods','GET,POST,DELETE,PUT,OPPINS')
    // 下一步
    next()
})
// 中间件   扩展了req.body功能
// 所有中间件   一般都写到  请求的最上方
app.use(express.urlencoded({
    
    extended:true}))
// 给每个请求加一个时间戳
app.use(/.*/,function (req,res,next) {
    
    
    // 加一个本地时间
    console.log(new Date().toLocaleString());
    // 不要忘记  next
    next();
})
app.get("/home",(req,res)=>{
    
    
    res.json({
    
    
        code:1000,
        msg:"成功"
    })
})
// -------jsonp  也是get请求
app.get("/ajaxJsonp",(req,res)=>{
    
    
    console.log("jsonp参数:",req.query);
    // 只有jsonp请求   对应返回用的是jsonp
    let{
    
    name,pwd} = req.query;
    if (name === "雨航" && pwd === "yh163.com") {
    
    
        res.jsonp({
    
    
            code:1000,
            msg:"jsonp-成功"
        })
    } else {
    
    
        res.jsonp({
    
    
            code:1000,
            msg:"jsonp-失败"
        })
    }
})
// -------get
app.get("/ajaxGET",(req,res)=>{
    
    
    console.log("get参数:",req.query);
    // 只有jsonp请求   对应返回用的是jsonp
    let{
    
    name,pwd} = req.query;
    if (name === "雨航" && pwd === "yh163.com") {
    
    
        res.json({
    
    
            code:1000,
            message:"get-成功"
        })
    } else {
    
    
        res.json({
    
    
            code:1000,
            message:"get-失败"
        })
    }
})
// -------post
// express 接收到的post请求数据   都存储在req对象的body属性里
app.post("/ajaxPOST",(req,res)=>{
    
    
    console.log("post参数:",req.query);
    console.log("post参数-2:",req.body);
    
    let{
    
    name,pwd} = req.body;
    if (name === "雨航" && pwd === "yh163.com") {
    
    
        res.json({
    
    
            code:1000,
            message:"post-成功"
        })
    } else {
    
    
        res.json({
    
    
            code:1000,
            message:"post-失败"
        })
    }
    // 只有jsonp请求   对应返回用的是jsonp
    //  经过排查  是因为多写了这段代码,下面的res.json()删掉/注释掉
    res.json({
    
    
        code:1000,
        message:"post-成功"
    })
})
app.listen(9201,()=>{
    
    
    console.log("9201  启动");
})

After investigation, it was found that the last
res.json ({ code: 1000, message: "post-successful" }) caused the server to error in calling Serverresponse.json multiple times. After commenting out this code, the error will be disappear



The reason is:
res.json has a built-in writeHeader method. If we execute res.json one more time, it is equivalent to writing writeHeader one more time. However, the previous res.json has already sent the data to the client, so we execute res.json again. , writeHeader needs to be executed again, so an error is reported: Can't set headers after they are sent.

The front-end page code is like this

<!--
 * @Author: bkk
 * @weixin: biankuan1996
 * @email: [email protected]
 * @Date: 2021-06-16 16:03:59
 * @LastEditTime: 2021-06-17 11:11:09
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>

</head>
<body>
    <input type="text" placeholder="请输入用户名" id="username">
    <input type="text" placeholder="请输入密码" id="userpwd"><br>
    <button>get</button>
    <button>post</button>
    <button>jsonp</button>
    <script>
        // get
        $('button').eq(0).click(function(){
      
      
            $.ajax({
      
      
                type: "get",
                url: "http://127.0.0.1:9201/ajaxGET",
                data: {
      
      
                    name:username.value,
                    pwd:userpwd.value
                },
                dataType: "json",
                success: function (response) {
      
      
                    console.log("get---",response);
                    alert(response.message)
                }
            });
        })
         // post
         $('button').eq(1).click(function(){
      
      
            $.ajax({
      
      
                type: "post",
                url: "http://127.0.0.1:9201/ajaxPOST",
                data: {
      
      
                    name:username.value,
                    pwd:userpwd.value
                },
                dataType: "json",
                success: function (response) {
      
      
                    console.log("post---",response);
                    alert(response.message)
                }
            });
        })
         // get
         $('button').eq(2).click(function(){
      
      
            $.ajax({
      
      
                type: "get",
                url: "http://127.0.0.1:9201/ajaxJsonp",
                data: {
      
      
                    name:username.value,
                    pwd:userpwd.value
                },
                dataType: "jsonp",
                jsonpCallback:"getData"
            });
        })
        function getData(data) {
      
      
            console.log("jsonp------:",data);
            alert(data.msg)
        }
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/m0_56026872/article/details/117988715