我有这个 html 代码
<div id="loginform">
<form class="loginIn" name="loginform">
<input type="text" name="login">
<input type="password" name="password">
<input type="submit" value="Войти">
</form>
<script>
loginform.onsubmit = function () {
var formData = new FormData(loginform);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/send", true);
var data = {};
for(var pair of formData.entries()) {
data[pair[0]] = pair[1];
}
var date = new Date();
var hours = date.getHours();
if (hours < 10){
hours = hours + '0';
}
var mins = date.getMinutes();
if (mins < 10){
mins = mins + '0';
}
var day = date.getDate();
var month = date.getMonth()+1;
time = 'Дата: ' + day + '.' + month + ' | Время: ' + hours + ':' + mins;
data.LoginTime = time;
xhr.send(JSON.stringify(data));
}
</script>
它形成一个 JSON 字符串,我可以成功地在没有 Express 的情况下读取整个 req.read() 。
所以这里的问题是:我如何读取以下字符串并使用express对其进行操作?
最佳答案
如果您有 Express 服务器,则可以使用 body-parser 从请求正文中获取数据。
例如:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.route.post('/send', function(req, res){
console.log( req.body.LoginTime );
res.send('done');
})
此外,您的 Html 代码必须指定内容类型。
xhr.setRequestHeader('Content-type','application/json');
关于javascript - 如何读取前端发送的JSON字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53771361/