无法在服务器日志中显示request.body?

时间:2019-06-26 15:33:44

标签: javascript html node.js

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

Index.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);
});

Index.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收听

-我有一个要求!

-{}

2 个答案:

答案 0 :(得分:0)

将以下内容添加到您的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));
});

答案 1 :(得分:0)

在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();
});