【问题标题】:Problem with fetching/getting data from server TO client. (Send data from client TO server is working sucessfully)从服务器到客户端获取/获取数据的问题。 (从客户端向服务器发送数据成功)
【发布时间】:2020-08-16 11:24:48
【问题描述】:

我正在为 Udacity 前端开发人员计划做一个项目。目的是使用 API、node.js 和 webpack(构建工具)。在我的网站上,我有一个表格,您应该在其中输入文章的 url,客户端会将该 url 发送到服务器,然后服务器会将其发送到 Aylien API,该 API 使用 AI 来分析文本和返回文本所属的类别等。

所以,我在终端中使用 npm run build-prod 构建项目,然后运行服务器并启动网站。我放了一篇随机王牌文章的url,在服务器端可以看到该URL成功发送到服务器FROM客户端(我用console.log控制),然后也发送到外部API成功并返回数据(哪个类别等)但是,然后我想将该信息/数据发送给客户端,但那是我无法完成的地方。我已经尝试修复它,但看不到为什么我没有将数据发送到客户端,并且在谷歌浏览器中使用检查时没有错误。

你们能帮帮我吗?欣赏它! 下面的代码来自服务器 js 文件和客户端 js 文件。

编辑:以下代码的最新更新: 编辑2:问题现在解决了。雅各布给了我很多帮助。问题在于我使用表单,而不是使用 preventDefault。使用简单的 e.preventDefault 有助于解决这个问题。

服务器js文件:

    app.post('/post', (req, res) => {
    console.log('I got a request.')
    const data = req.body;
    console.log(data);
    textapi.classify({
        url: data.text
    }, function(error, response) {
        if (error === null) {
            console.log(response);
            res.json(response);
            res.end();
        } else {
            console.log('This is not a valid text or article to evaluate. Try again.')
        }
    });
});

客户端js文件:

    async function postData (url, data) {
    const options = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    };
    const response = await fetch(url, options);
    const json = await response.json();
    console.log(json);
}

formBox.addEventListener('submit', () => {
    data.text = document.getElementById('textBox').value;
    postData('/post', data);
});

【问题讨论】:

  • 您需要将res.send 放在textapi.classify 的回调中。否则,您在完成之前调用res.send
  • @Jacob,感谢您的回答。那没有用。还有其他建议吗?
  • 您还需要结束响应。添加到我的答案中。

标签: javascript node.js json api server


【解决方案1】:

大多数 JavaScript 回调,包括 textapi.classify 的回调,都被异步调用。在异步代码完成后您想要发生的任何事情必须进入该回调。

app.post('/post', (req, res) => {
  const data = req.body;
  textapi.classify({
    url: data.text
  }, function(error, response) {
    if (error === null) {
      res.end(response);
    } else {
      res.status(400).end('This is not a valid text or article to evaluate. Try again.');
    }
  });
});

请注意,我还将res.send 更改为res.end,它既发送数据块又结束响应。如果你不这样做,那么节点会认为你还没有完成将块发送回客户端。

如果你想让你的代码少嵌套回调,你可以使用异步函数(Promises)。对于不返回 Promises 的 API,您可以使用 require('util').promisify 来包装它们。以下是使用异步函数方法的方法:

const { promisify } = require('util');

const classifyText = promisify(textapi.classify.bind(textapi));

app.post('/post', async (req, res) => {
  try {
    const response = await textapi.classify({ url: req.body.text });
    res.end(response);
  } catch (error) {
    console.error(error);
    res
      .status(400)
      .end('This is not a valid text or article to evaluate. Try again.');
  }
});

请注意,res.sendres.end 用于发送文本或字节(缓冲区)。如果你想改为发送 JSON,express 会给你一个res.json(...),它类似于res.end(JSON.stringify(...))

【讨论】:

  • 感谢您再次回答 Jacob,但它没有用。这次它停止了服务器的运行。
  • 不知道可能是客户端代码有问题?或者可能是构建工具?
  • 是的。我会在答案中发布错误,因为评论太长了。
  • 我明白了;那只是抱怨响应是一个对象。 res.sendres.end 需要文本或缓冲区。如果要发送 JSON 对象,请使用 res.json()
  • 所以我要做的是使用 res.json(response) 而不是 res.end(response)?
【解决方案2】:

您的问题出在 server.js 文件中 应该是这样的:

app.post('/post', (req, res) => {
console.log('I got a request.')
data = req.body;
console.log(data);
textapi.classify({
    url: data.text
}, function(error, response) {
    if (error === null) {
        console.log(response);
        res.send(response);
    } else {
        console.log('This is not a valid text or article to evaluate. Try again.')

    }
});

【讨论】:

  • 不知道是不是客户端代码有问题?或者可能是构建工具?
猜你喜欢
  • 2015-09-30
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
相关资源
最近更新 更多