【问题标题】:How to read JSON string sent from the frontend如何读取从前端发送的 JSON 字符串
【发布时间】:2018-12-13 23:07:57
【问题描述】:

我有这个 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 字符串,我可以成功地在整个 req.read() 中读取,而无需表达。

所以这里的问题是:我如何读取以下字符串并使用 express 对其进行操作?

【问题讨论】:

  • 您是否设置了快速服务器?如果是这样,您能否发布一些服务器代码?

标签: javascript node.js json express


【解决方案1】:

如果你有一个 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');

【讨论】:

    【解决方案2】:

    您可以使用 body-parse 来获取客户端发送的参数。

    首先将 body-parse 下载到您的项目中

    npm install body-parse --save
    

    那么你可以在 express 中编写这样的服务:

    const express = require('express');
    const bodyParser = require('body-parser');
    
    var app = express();
    var router = express.Router();
    
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    
    router.post('/send', (req, res)=>{
        console.log( req.body );
        res.send(req.body);
    });
    

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      相关资源
      最近更新 更多