【问题标题】:Can't display request.body in server log?无法在服务器日志中显示 request.body?
【发布时间】:2019-06-27 00:09:43
【问题描述】:

我是 Node 新手,我似乎无法完成我的请求。我只是试图通过将客户端的位置发送到服务器并将其显示到服务器日志中来创建服务器和客户端之间的基本握手。我不确定为什么我无法将数据显示到日志中。

索引.js

const express = require('express');
const app = express();
app.listen(8080, () => console.log('listening at 8080'));
app.use(express.static('public'));
app.use(express.json({limit: '1mb'}));

app.post('/api',(request,response) => {
    console.log('I got a request!');
console.log(request.body);
});

索引.html

 <script>
        if('geolocation' in navigator) {
            console.log('geolocation is avaliable');
            navigator.geolocation.getCurrentPosition(async position => {
                const lat = position.coords.latitude;
                const lon = position.coords.longitude;

                console.log(lat,lon);
                document.getElementById('latitude').textContent = lat;
                document.getElementById('longitude').textContent = lon;

                const data = {lat, lon};
                const options = {
                    method: 'POST',
                    header:{
                        'Content-Type':'application/json'
                    },
                    body: JSON.stringify(data)
                };
                fetch('/api',options);
            });
        } else{
            console.log('geolocation is not avaliable');
        }
    </script>

一些注意事项。请求似乎已完成,开发者控制台中未显示任何错误。

服务器信息: -[nodemon] 由于更改而重新启动...

-[nodemon] 起始节点index.js

-在 8080 收听

-我有一个请求!

-{}

【问题讨论】:

  • 您是否尝试过对请求正文进行字符串化?
  • 我该怎么做?
  • JSON.stringify(request.body)
  • Uncaught (in promise) ReferenceError: request is not defined 是我得到的响应错误
  • @Harsh 什么版本的快递?同一个你从那个例子那里得到的?

标签: javascript html node.js


【解决方案1】:

将以下内容添加到您的index.js

npm i -S body-parser
// Takes the raw requests and turns them into usable properties on req.body
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.post('/api', (request, response) => {
  console.log('I got a request!');
  console.log(JSON.stringify(request.body));
});

【讨论】:

  • 我试了一下,你想让我和JSON.stringify(request.body) 一起使用吗?如果没有,我会收到 ReferenceError: bodyParser is not defined 错误
  • @Harsh 更新了帖子,是的,具体取决于您尝试控制台日志的内容,您必须进行字符串化。
  • 在编辑之后,我又遇到了一些错误。如果有帮助,他们就在这里 - npm ERR!代码 E404 | npm 错误! 404 未找到 - 获取 registry.npmjs.org/bodyParser - 未找到 | npm 错误! 404 'bodyParser@latest' 不在 npm 注册表中。
  • @Harsh 对包 body-parser 的拼写错误
  • 好的,我明天试试。现在发生了一些事情,所以我们将看看它是否有效。感谢您迄今为止的帮助
【解决方案2】:

在您的 index.js 中尝试以下代码

    const express = require('express')
const app = express();
const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*")
    res.header(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept, Authorization"
    );
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET')
    }
    next();
});

【讨论】:

  • 它在 nodemon 中告诉我 clean exit - waiting for changes before restart
猜你喜欢
  • 2019-12-10
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-07
  • 2019-04-05
  • 2019-09-09
相关资源
最近更新 更多