我正在为 Udacity 前端开发人员计划做一个项目。目的是使用 API、node.js 和 webpack(构建工具)。在我的网站上,我有一个表单,您应该在其中输入文章的 url,客户端将将该 url 发送到服务器,然后服务器将其发送到 Aylien API,后者使用 AI 来分析文本和返回文本具有的类别等。
所以,我在终端用 npm run build-prod 构建项目,然后运行服务器并启动网站。我随便放了一篇王牌文章的url,在服务器端可以看到该URL从客户端成功发送到服务器(我用console.log来控制),然后也发送到外部API 成功并返回数据(哪个类别等)但是,然后我想将该信息/数据发送给客户端,但这是我无法完成的地方。我试过修复它,但不明白为什么我没有将数据发送到客户端,并且在 Google Chrome 中使用检查时没有错误。
你们能帮我吗?欣赏它!以下代码来自服务器 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);
});
大多数 JavaScript 回调,包括 for 回调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)。对于不返回 Promise 的 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.send
和res.end
用于发送文本或字节(缓冲区)。如果你想发送 JSON,express 会给你一个res.json(...)
类似于res.end(JSON.stringify(...))
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句