我正在尝试使用Node.JS为我的前端网页创建一个后端。该网页使用谷歌翻译API并翻译用户词。目前,当我对单词和语言进行硬编码时,我能够使其工作。我想要做的是检索他们输入的单词和他们想要翻译的语言。
前端代码
function translateWord() {
var url = 'http://localhost:8085';
var endpoint = '/translate';
var fromLang = document.getElementById("fromLang").value;
var toLang = document.getElementById("toLang").value;
var word = document.getElementById("wordInput").value;
var payload = {"word": word, "from": fromLang, "to": toLang};
console.log(payload);
var http = new XMLHttpRequest();
http.open("POST", url+endpoint, true);
http.setRequestHeader("Content-type", "application/json");
http.onreadystatechange = function() {
var DONE = 4; // 4 means the request is done.
var OK = 200; // 200 means a successful return.
if (http.readyState == DONE && http.status == OK && http.responseText) {
var reply = http.responseText;
document.getElementById("mainBody").innerHTML = reply;
}
};
var params = JSON.stringify(payload);
// Send request
http.send(params);
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Translation Demo</title>
<link rel="stylesheet" href="css/main.css" type="text/css">
</head>
<body>
<script src="js/main.js"></script>
<div>
<h1> Translation Demo </h1>
<p>Word:<input id="wordInput" type="text"></p>
<p>From:
<select id="fromLang">
<option value="en" selected>English</option>
<option value="fr">French</option>
<option value="es">Spanish</option>
<option value="ru">Russian</option>
</select>
To:
<select id="toLang">
<option value="en">English</option>
<option value="fr" selected>French</option>
<option value="es">Spanish</option>
<option value="ru">Russian</option>
</select>
</p>
<button onclick="translateWord()">Translate</button>
<p id="mainBody">Translation here.</p>
</div>
</body>
</html>
&#13;
这是我遇到问题的后端(这部分因为硬编码而起作用)。
var express = require('express');
var router = express.Router();
var cors= require('cors');
router.use(cors());
router.post('/translate', function(req, res)
{
var payload = req.body;
var word = "hello";
var json = { from: 'en', to: 'fr' };
const translate = require('google-translate-api');
translate(word, json).then(function (resolve, reject){res.send(resolve.text.toString());});
});
module.exports = router;
为了能够抓住单词和语言,我尝试按照这个方法做一些事情。我还有8085端口,所以不是问题。
var payload = req.body;
var word = req[word];
var from = req[from];
var to = req[to];
var json = { from: 'from', to: 'to' };
当我尝试这样做时,我收到此错误。
(node:6892) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property 'length' of undefined
有人能指出我正确的方向,我做错了吗?我一直在努力解决这个问题,而且还没有能够解决这个问题。
答案 0 :(得分:0)
默认情况下,ExpressJS无法解析JSON帖子数据。要解决此问题,您可以使用body-parser
模块。
安装它:
a b
0 it_python
1 my_shark
2 my_shark
3 the_panda
4 my_shark
5 my_shark
a b
0 it_python python
1 my_shark shark
2 my_shark shark
3 the_panda panda
4 my_shark shark
5 my_shark shark
并在代码中使用它:
npm i -S body-parser
然后,在该功能中,您将能够访问您的数据:
var express = require('express');
var bodyParser = require('body-parser'); // <----------------------------
var jsonParser = bodyParser.json(); // <----------------------------
var router = express.Router();
var cors= require('cors');
router.use(cors());
router.post('/translate', jsonParser, function (req, res) // <-----------
{
/* ... */
});
module.exports = router;