【问题标题】:How to send json data to client side from express nodejs如何从express nodejs将json数据发送到客户端
【发布时间】:2021-10-07 23:21:49
【问题描述】:

我有一个应用程序,我需要通过 XMLHttpRequest 发送表单数据。当我发送该信息时,我需要验证表单,然后根据表单是否验证将信息发送回客户端。我正在使用 nodejs 和 express。

我的客户端代码是:

editor.save().then((output) => {
  let formData = new FormData();
  const xhr = new XMLHttpRequest();
  formData.append('name', document.getElementById('inputProductName').value);
  xhr.open('post', '/items/add', true);
  xhr.send(formData);
}).catch((error) => {
  console.error('Error: ' + error);
  return;
}).finally(() => {
  // This is where I need to retrieve the validation code and redirect accordingly.
  if (success == false) {
    window.location.href = '/items/add/failed';
  } else {
    window.location.href = '/items/add/success';
  }
});

我的服务器端代码是这样的:

router.post('/add', (req, res) => {
  let form = new formidable.IncomingForm();
  form.parse(req, (err, fields, files) => {
    if (fields.name.length < 1) { // If the name is empty
      res.status(200).json({
        success: false,
        message: 'Product name must be specified'
      });
    } else {
      res.status(200).json({
        success: true,
        message: 'Product added successfully'
      });
    }
  });
});

所以如果验证失败,那么如果可能的话,我希望能够通过客户端获取成功和消息变量。

【问题讨论】:

  • 你写的代码有什么问题?
  • 我的客户端控制台出现错误,提示未定义成功。我最初只是想尝试使用 Flash 消息传递和 res.redirect,但它不起作用,这就是我在客户端重定向的原因。
  • 为什么要定义success?这是一个你无论如何都没有定义的变量。而且您正在向 XHR 发出请求,但从不查看响应。 (如果您仍然使用 Promise,为什么要使用 xhr 而不是 fetch?)
  • 我对 javascript 还很陌生,当我在 Google 上搜索发送表单数据时,xhr 是第一个出现的东西,所以我选择了它。我应该改用 fetch 吗?

标签: javascript node.js json express client


【解决方案1】:

看看using fetch API from MDN docs

  • 通过POST获取数据
  • await回复
  • 根据response.success采取相应措施

此外,查看服务器端代码,似乎没有必要使用form encoding

  • 建议以 json 格式发送数据,并让服务器检查 request.body 以获取要填充的适当字段。

伪代码

editor.save().then(async (output) => {
  let formData = new FormData();
    formData.append('name', document.getElementById('inputProductName').value);
    const response = await fetch(url, {
    method: 'POST',
    // ... additional form data here, looks like you can send JSON, no need for form encoding
    }
    if(response.success) {
      window.location.href = '/items/add/success';
    } else {
      window.location.href = '/items/add/failed';
    }

}).catch((error) => {
  console.error('Error: ' + error);
  return;
})

请注意,匿名函数 () =&gt; {} 现在是 async () =&gt; {},以允许 await 调用 fetch

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2020-02-28
    • 2019-03-05
    • 2015-08-02
    • 2022-01-12
    相关资源
    最近更新 更多