错误:发送后设置标头-帮助我了解原因? [英] Error: Setting header after it is sent - Help me understand why?

查看:56
本文介绍了错误:发送后设置标头-帮助我了解原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道将标头发送给客户端后如何设置标头吗?

代码:在表单提交过程中,发出了ajax请求,响应是一个返回给客户端的json对象.

code: During form submission a post ajax request is made, the response is a json object that is returned to the client.

我被注释掉了大部分代码,以找出原因,目前,我仅在发出发布请求后才执行一个res.json().我不知道在什么时候我要重新设置标题/或两次返回响应?

I am commented out most of the code to find out why, at this point I am only doing one res.json() after a post request is made. I don't understand at what point I am RE-SETTING the header/ or returning a reponse twice?

但我收到此错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (/home/shahyan/Videos/FrontendProject-masters/notes-js/beginner/js-fundamentals-functional/todoApp/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/home/shahyan/Videos/FrontendProject-masters/notes-js/beginner/js-fundamentals-functional/todoApp/node_modules/express/lib/response.js:170:12)
    at done (/home/shahyan/Videos/FrontendProject-masters/notes-js/beginner/js-fundamentals-functional/todoApp/node_modules/express/lib/response.js:1004:10)
    at Object.exports.renderFile (/home/shahyan/Videos/FrontendProject-masters/notes-js/beginner/js-fundamentals-functional/todoApp/node_modules/pug/lib/index.js:412:12)
    at View.exports.__express [as engine] (/home/shahyan/Videos/FrontendProject-masters/notes-js/beginner/js-fundamentals-functional/todoApp/node_modules/pug/lib/index.js:455:11)
    at View.render (/home/shahyan/Videos/FrontendProject-masters/notes-js/beginner/js-fundamentals-functional/todoApp/node_modules/express/lib/view.js:135:8)
    at tryRender (/home/shahyan/Videos/FrontendProject-masters/notes-js/beginner/js-fundamentals-functional/todoApp/node_modules/express/lib/application.js:640:10)
    at Function.render (/home/shahyan/Videos/FrontendProject-masters/notes-js/beginner/js-fundamentals-functional/todoApp/node_modules/express/lib/application.js:592:3)
    at ServerResponse.render (/home/shahyan/Videos/FrontendProject-masters/notes-js/beginner/js-fundamentals-functional/todoApp/node_modules/express/lib/response.js:1008:7)

index.js

var express = require('express');
var router = express.Router();

let users = [];



/* GET home page. */
router.get('/', function(req, res, next) {

  res.render('index', { title: 'Express' });
});

router.post('/', function(req, res, next) {
  // check post valued are true
  if(req.body.fname && req.body.list_name && req.body.list_date) {
    // try {
       addNewUser(req.body);
       res.json({
         "message":"Successfully signed up!",
         "userName": req.body.fname,
         "userDate": req.body.list_date
        });
    // } catch(e){
      // signup failed
      // res.json(res.status(status).json(obj), "Sign up failed...");
    // }
   }
  //  if(req.body.list_item) {
  //    console.log(req.body.list_item);
  //  }
   console.log(body.req);

});
module.exports = router;

function addNewUser(data) {
  try {
    users.push(
      {
        "fname":data.fname,
        "list_name": data.list_name,
        "list_date": data.list_date
      }  
    );  
  } catch(e) {
    console.log("Failed to add user ", e);
      throw e;
  }

}

myscript.js ---前端客户端

myscript.js --- front end client side client

document.getElementById("createNewList").addEventListener('submit', function(e) {
    e.preventDefault();

    // serialize form to convert into JSOn object
    let form_data = formSerialize(document.getElementById("createNewList"));

     // AJAX fetch()
    fetch('/', {
        method: 'POST',
        headers: {
            "Content-Type": "application/json; charset=utf-8",
            // "Content-Type": "application/x-www-form-urlencoded",
        },
        body: form_data
    })
    .then(function(response) {      
         if(response.ok)
            return response.json();
    })
    .then(function(user_json) {
        console.log(user_json);

        console.log(user_json);
        create_todays_todo_list(user_json);
    });
});

// add event listener of the to do list i.e. adding tasks deleting tasks, completed tasks
// document.getElementById("toDoList_form").addEventListener('submit', function(e) {
    // e.preventDefault();
    // console.log("clikeddddddddd");
    // // AJAX send added task to server
    // let list_item = document.getElementById("list_item").innerHTML;
    // let user = document.getElementById("user_name_heading").innerHTML;
    // let data = {"user": user, "list_item": list_item}
    // console.log(data);
         // AJAX fetch()
        //  fetch('/', {
        //     method: 'POST',
        //     headers: {
        //         "Content-Type": "application/json; charset=utf-8",
        //         // "Content-Type": "application/x-www-form-urlencoded",
        //     },
        //     body: data
        // })
        // .then(function(response) {
        //      if(response.ok)
        //         return response.json();
        // })
        // .then(function(retrievedItemsFromServer) {
        //     console.log(retrievedItemsFromServer);
        // });

    //
// });


/// functionssss
// serialize form function
function formSerialize(form) {
    var input = form.getElementsByTagName("input");
    var formData = {};
    for (var i = 0; i < input.length; i++) {
      formData[input[i].name] = input[i].value;
    }
    return formData = JSON.stringify(formData);
  }
function create_todays_todo_list(user_json) {
    // 1. hide the create list form  form
    document.getElementById("createNewList").style.display="none";

    // 2. display the to do list div
    document.getElementById("toDoList").style.display="flex";

    // 3. display the user's name and date as logged in on the page
    document.getElementById("user_name_heading").innerHTML = user_json.userName;
    document.getElementById("user_date_signup_heading").innerHTML = user_json.userDate;

}

推荐答案

console.log(body.req); 这是错误的.它应该是 console.log(req.body); .通常在程序退出但堆栈中仍然存在函数回调时会发生这种情况.这应该可以解决您的问题.如果没有,请共享控制台日志(如果有的话)

console.log(body.req); this is wrong. It should be console.log(req.body);. This generally happens when the program exited but still, there is a function callback in the stack. This should fix your problem. If it didn't please share the console log if printed any

这篇关于错误:发送后设置标头-帮助我了解原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆