Node JS中的多个POST请求问题

时间:2020-05-14 13:37:19

标签: javascript node.js json forms post

所以我一直在构建一个Web应用程序,并且已经实现了POST请求,以请求将一些JSON数据发送到Node JS服务器,但是当我现在尝试为另一组数据添加第二条消息时, HTML表单我收到一个Cannot POST / x /页面,但是,如果我对第一组数据使用先前的POST URL,则数据将正确发送。发送多个POST请求是否有问题?我在下面添加了一些代码,因此您可以看到我的正常工作/ foo / JSON数据请求与不正常的/ basket / HTML表单请求。提前谢谢。

工作代码:

    app.post("/foo/", function(req, res) {

    var myObject = req.body;

    console.log(myObject);

    for(var i = 0; i < myObject.length; i++){
        var parsed = JSON.parse(myObject[i])
        console.log(parsed.Item.ProductNo);
        console.log(parsed.Item.Quantity);
    }

    var transporter = nodemailer.createTransport({
  service: '*****',
  auth: {
    user: '*****',
    pass: '*****'
  }
});

不起作用的请求:

    app.post("/basket/"), function(req, res){
    var body = req.body;
    console.log(body);
}

正在处理foo请求JS:

function sendBasket(){

    fetch('/foo/', {
  method: 'post',
  headers: {
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
  },
  body: localStorage.getItem('basket')
}).then(res=>res.json())
  .then(res => console.log(res));

    console.log('Sending' + basketList + 'To email');
    //console.log(localStorage.getItem('basket'));
    //$.post("/foo/", localStorage.getItem('basket'), function(temp) {
    // temp === "I am done";    
//});


}

无法使用HTML表单请求:

form#customerForm(method = 'post' action = '/basket/')
            input(class='input' id='email' name='email' type='email' value='')
            ul#listForBasket.listForBasket
            input#butSubmit(type = 'submit' value = 'submit')

1 个答案:

答案 0 :(得分:0)

答案:我仍然不太确定如何解决它,但是问题现在已经解决,我相信这是由于HTML表单中Action属性的使用不正确以及JS中的结构化获取请求不正确文件以及结构错误的server.js文件。非常感谢u / fasticious-magician在诊断我的问题方面提供了很大的帮助。这是我在JS中最后一次正常的第二次提取请求:

function sendData(e){
    e.preventDefault();
    const email = document.getElementById("email").value;
    const bodyToSubmit = { "email": email }
    console.log(JSON.stringify(bodyToSubmit))
    fetch('/foo2/', {
          method: 'post',
          headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
              },
          body: JSON.stringify(bodyToSubmit)
            }).then(res=>res.json())
              .then(res => console.log(res));
}