【问题标题】:ExpressJS doesn't receive the response in a postExpressJS 没有收到帖子中的响应
【发布时间】:2017-04-04 12:40:28
【问题描述】:

希望你能帮助我:

我的 localhost 中有一个 API 作为前端和数据库之间的桥梁。

我在前端服务器中使用 Express。当我提交表单时,数据被放入数据库中,我的 API 按我的预期发送响应,但 express 没有收到任何内容,并且状态处于挂起状态(几分钟后,我的浏览器拒绝响应):

这是我使用 express 的代码(ClientApi 是我在 localhost 中运行的自定义 API 的实例):

lisaApp.post('/signup', (req, res) => {
  const validationResult = validateSignupForm(req.body);
  if (!validationResult.success) {
    return res.status(400).json({
      success: false,
      message: validationResult.message,
      errors: validationResult.errors
    });
  }

  var newClient = req.body
  newClient.clientemailname = newClient.userclient
  newClient.client_id = uuid.v4()

  delete newClient.confirmPassword

  ClientApi.saveClient(newClient, function (err, usr) {
    if (err) return res.status(500).send(err.message)

    console.log('entro')
    res.redirect('/')
  });

});

这是我的 API 的函数,它按预期返回响应(请参阅我使用 Access-Control-Allow-Origin 设置了我的标头):

hash.set('POST /', async function saveClient (req, res, params) {
  let client = await json(req)

  if (!db.connected) {
    await db.connect()
  }

  let createdClient = await db.saveClient(client)

  delete createdClient.clientemailname
  delete createdClient.password

  await db.disconnect()
  res.setHeader('Access-Control-Allow-Origin', '*')
  send(res, 201, createdClient)
})

通过表单发送数据后,这是我的浏览器显示的错误 我:

Failed to load resource: net::ERR_EMPTY_RESPONSE
Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
    at app.js:18952

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    hash.set('POST /', async function saveClient (req, res, params) 定义中,res 对象上没有调用 send(arguments here>) 方法/函数。 如果您专门定义了 send(arguments here>) 方法/函数,请确保它调用 res.end(arguments here >) 或 res.write(arguments here>) 后跟 res.end(arguments here> )。

    如果不需要专门的 send(arguments here>) 方法/函数,那么在我看来,您可能需要调用 res.end(arguments here em>>) 或 res.write(arguments here>) 后跟 res.end(arguments here>) 而不是 send(arguments here>) 方法/函数。

    【讨论】:

    • 好的,你帮了我很大的忙,谢谢。现在我收到了响应,但无法实现应用程序重定向到另一个链接。我正在使用反应(我现在正在学习)。您现在对此有所了解吗?
    猜你喜欢
    • 2015-03-25
    • 1970-01-01
    • 2014-07-14
    • 2016-07-08
    • 2023-03-23
    • 2019-07-11
    • 2014-05-02
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多