我已使用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,其中有我的提取函数。
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))
}
})
答案 0 :(得分:2)
您请求中的Content-Type
标头必须是application/json
而不是application
答案 1 :(得分:1)
let response = await fetch('http://*******', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(params),
});