javascript - 如何读取前端发送的JSON字符串

标签 javascript node.js json express

我有这个 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/

相关文章:

javascript - 如何判断 Vue 组件是否已卸载以防止异步函数访问已卸载组件的数据?

javascript - 实现在 Angular2 中对对象数组进行排序

javascript - 使用 ruby​​ 设置基本的本地服务器

javascript - 将每次迭代中的 html 附加到单个 div

javascript - electron项目中如何集成qt native window?

javascript - 如何用生成的子进程替换 node.js 进程?

javascript - 为 Node.JS 加载自定义 CSS 处理程序

iphone - 使用 Asihttprequest 和 iphone 的 Json 框架解析 JSON 数据

javascript - 在 JavaScript 中重新排序 JSON 列表集合

android - 如何从 JSON 数组获取字符串