Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在“表单”之后发送空的{};邮政「;在node.js中使用pug_Javascript_Node.js_Forms_Express_Pug - Fatal编程技术网

Javascript 在“表单”之后发送空的{};邮政「;在node.js中使用pug

Javascript 在“表单”之后发送空的{};邮政「;在node.js中使用pug,javascript,node.js,forms,express,pug,Javascript,Node.js,Forms,Express,Pug,我试图通过post使用fetch将表单数据从登录页面传递到登录页面,并使用以下pug代码: form(id="form-login") input(type="text", name="email", value="", placeholder="Tu email") br input(type="password", name="password", value="", placeholder="Tu contraseña") br input(type

我试图通过post使用fetch将表单数据从登录页面传递到登录页面,并使用以下pug代码:

form(id="form-login")
    input(type="text", name="email", value="", placeholder="Tu email")
    br
    input(type="password", name="password", value="", placeholder="Tu contraseña")
    br
    input(type="submit" value="Conectar")
script.
    const formLogin = document.querySelector('#form-login');
    const formData = new FormData(formLogin);

    formLogin.addEventListener('submit', function(event) {
        console.log('Form Data: ', formData);
        event.preventDefault();
        fetch('/signin', {
            method: 'POST',
            body: formData
        })
        .then(function(res) {
            res.json();
        })
        .then(function(data) {
            console.log(data)
            localStorage.setItem('token', data.token)
        })
    });
问题是到达登录的请求正文为空。。跟踪之后,它会给出这个console.log

Form Data:  FormData {}
还有一个未定义的req.body。 如果我对这个脚本进行注释,并通过添加
action=“/sign”和method=“post”
的表单发送它,它会工作并打印答案,但是调用
storage.setItem({token:})
返回一个
Uncaught(in-promise)类型错误:无法读取未定义的属性“token”
我想知道为什么这个脚本不发送数据。。。不明白。。。因此,任何帮助都将非常感激

登录功能:

function signIn (req, res) {    
    if (!req.body.email) return res.status(200).send({message: 'No recibo el usuario'})

    User.findOne({ email: req.body.email }, (err, user) => {

        if(err) return res.status(500).send({ message: err })
        if(!user) return res.status(404).render('login', { title: 'Intenta loguearte de nuevo' })

        user.comparePassword(req.body.password, (error, isMatch) => {
            if (error) return res.status(500).send({ message: error })
            if (!isMatch) {
                return res.redirect('login')
            } else {
                req.user = user
                res.status(200).send({
                    message: 'Te has logueado correctamente',
                    token: service.createToken(user)
                })
                //$window.localStorage.setItem({token: service.createToken(user)}); // NO WORKS
                return res.body = service.createToken(user) // TRYING THIS WITHOUT KNOWLEDGE ABOUT WHAT AM I DOING :O
            }
        })                 
    })
}
提前谢谢

****编辑**** 正如@MichałSałaciński所建议的,首先评论
,然后再评论res.json()…
,至少给出了一个回应,但仍然不理解这里发生了什么,为了正确地学习并使事情变得更好,也希望有人能解释如何正确地做这样的事情

  Response: body : ReadableStream
locked : false
__proto__ : Object
bodyUsed :   false
headers :  Headers
__proto__  :  Headers
ok :  true
redirected :  false
status : 200
statusText: "OK"
type  :   "basic"
您应该将“new FormData”移动到“send”事件侦听器中。此外,type=“submit”后缺少逗号,但总体而言,问题与帕格无关:)


因此,我遇到了同样的问题,来自我的pug表单的POST请求将一个空的
{}
作为
req.body
对象发回。该代码是一个简单的创建操作,使用以下内容:

bookController.js

exports.createBookForm = (req,res) => {
  res.render("create_book_form", { title: "Add A New Book"})
}

exports.createBook = (req,res) => {
  const reqFields = ["title", "author"];

  for (let i = 0; i < reqFields.length; i++) {
    const field = reqFields[i];

    if (!field in req.body) {
      const message = `Missing ${field} in the request body`;
      console.log(message)
      return res.status(400).send(message)
    }
  }

  Book
    .create({
      title: req.body.title,
      author: req.body.author,
      summary: req.body.summary
    })
    .then((book) => {
      res.status(201).json(book.serialize())
    })
    .catch(err => {
      console.log(err);
    })
}
最终修复了为POST操作显示实际req.body的是添加(在server.js中)


让我知道这是否适合你。我花了几个小时才得出这个结论,我讨厌看到问题没有答案。

我对帕格没有任何经验。将两个
调用链接在一起,然后像这样紧跟在一起是正常的吗?是的,据我所知,承诺在script标记中,因此在这一点上不应该与帕格冲突。是的,你可以链接。然后。在这里检查文档->最后,你找到解决方案了吗??我也有同样的问题!不适用于我,修复了缺少逗号和在函数中移动
const formData
的问题没有任何变化,仍然卡住。。。有人送了a-1。。。祝你有史以来最好的一天!是的,这里的否决票很奇怪,因为这个问题似乎完全正确。如果仍然不起作用,请尝试返回“return res.json();”,并尝试使用&不使用“body:formData”确定,尝试它,并获得以下响应:
response{type:“basic”,url:http://192.168.1.104:3000/signin,重定向:false,状态:200,确定:true…}正文:(…)bodyUsed:false Header:headers\uuuuu proto\uuuuuu:headers ok:true重定向:false状态:200状态文本:“ok”类型:“basic”url:“http://192.168.1.104:3000/signin“
看起来像是在响应内部。body也没什么:
body:ReadableStream locked:(…)\uuuuuuuuuuuuuuuuuuu:对象bodyUsed:false
exports.createBookForm = (req,res) => {
  res.render("create_book_form", { title: "Add A New Book"})
}

exports.createBook = (req,res) => {
  const reqFields = ["title", "author"];

  for (let i = 0; i < reqFields.length; i++) {
    const field = reqFields[i];

    if (!field in req.body) {
      const message = `Missing ${field} in the request body`;
      console.log(message)
      return res.status(400).send(message)
    }
  }

  Book
    .create({
      title: req.body.title,
      author: req.body.author,
      summary: req.body.summary
    })
    .then((book) => {
      res.status(201).json(book.serialize())
    })
    .catch(err => {
      console.log(err);
    })
}
block content
  h1 Add a Book
  h3 Do use real details. Otherwise, what's the point?

  form(method="POST" action="/books")
    div.form-group
      label(for="title") Title:
      input#title.form-control(type="text", placeholder="Small Gods" name="title")
      label(for="author") Author:
      input#author.form-control(type="text", placeholder="Terry Pratchett" name="author")
      label(for="summary") Summary:
      textarea#summary.form-control(type="text", placeholder="God is turtle, world is flat" name="summary")
      div.form-group
        button.btn.btn-primary(type="submit" role="submit") Add Book
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())