【问题标题】:node js express, req.body returns nothingnode js express,req.body什么都不返回
【发布时间】:2020-09-21 09:55:52
【问题描述】:

我用 express 设置了这个 web 服务器,一切正常,除了 req.body 似乎什么也没返回。我没有收到任何错误,它什么也没做。 console.log(req.body) 什么都不做。当我检查控制台时,我什么也看不到。但应用程序的其余部分工作正常。

我错过了什么?

server.js 文件在下面

if (process.env.NODE_ENV !== "production") {
    require("dotenv").config();
}

const clientId = process.env.client_id;
const clientSecret = process.env.client_secret;
const refreshToken = process.env.refresh_token;

const date = new Date();
date.setDate(date.getDate() - 2);

const express = require("express");
const app = express();

app.use(express.json());
app.use(express.static("public"));

app.post("/alerts", async (req, res) => {
    console.log(req.body)
    const alertsUrl = `https://www.g2smart.com/g2smart/api/alert?range=last7Days&cpo=${req.body.selection}&status=Opened&limit=100&page=1`
    const axios = require("axios");
    const oauth = require("axios-oauth-client");

    const getRefreshToken = oauth.client(axios.create(), {
        url: "https://www.g2smart.com/g2smart/api/oauth2/token",
        grant_type: "refresh_token",
        client_id: `${clientId}`,
        client_secret: `${clientSecret}`,
        refresh_token: `${refreshToken}`,
    });

    const auth = await getRefreshToken();

    axios({
        url: alertsUrl
            ,
        headers: {
            accept: "application/json, text/plain, */*",
            authorization: `Bearer ${auth["access_token"]}`,
        },
        responseType: "json",
    }).then((data) => res.json(data.data.items));
});

app.listen(process.env.port || 3000);

console.log("Running at Port 3000");

这是下面的 script.js,我有我的 fetch 函数。

const selectElement = document.querySelector('[data-cpo-select]')
const cpo = {
    france: "total_fr_hpc",
    netherlands: "total_nl_hpc",
    te61: "te61"}

selectElement.addEventListener("change", (event) => {
    const selection = event.target.value
    fetch("/alerts", {
        method: "POST",
        headers: {
            "Content-Type": "application",
            "Accept": "application/json", 
        },
        body: JSON.stringify({
            selection: cpo[selection]
        })
    })
        .then((res) => res.json())
        .then((data) => {
            setAlertsData(data);
        });


    const alertTypeElement = document.querySelector("[data-alert-type]");
    const locationElement = document.querySelector("[data-location]");
    const statusElement = document.querySelector("[data-status]");
    const severityElement = document.querySelector("[data-severity]");
    const chargePointElement = document.querySelector("[data-charge-point]");

    function setAlertsData(data) {
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        const today = new Date();
        locationElement.textContent = data["0"]["locationName"];
        severityElement.textContent = `${new Date(data["0"]["openDate"]).toLocaleString()} ${data["0"]["severity"]}`
        alertTypeElement.textContent = data["0"]["alertType"];
        chargePointElement.textContent = data["0"]["equipmentId"].slice(9,);
        statusElement.textContent = data["0"]["status"];

        console.log(new Date(data["0"]["openDate"]).toLocaleString(options))
    }
})

【问题讨论】:

  • 将标题更改为 'Accept': 'application/json''Content-Type': 'application/json'
  • 是的,这就是问题所在,在进行了这些更改后,它修复了它。谢谢!!!

标签: javascript node.js json express web


【解决方案1】:

您的请求中的 Content-Type 标头必须是 application/json 而不是 application

【讨论】:

  • 是的,解决了!非常感谢!
【解决方案2】:
let response = await fetch('http://*******', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    });

【讨论】:

    猜你喜欢
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2021-08-08
    • 1970-01-01
    • 2016-08-01
    • 2019-01-03
    • 2021-05-05
    相关资源
    最近更新 更多