我很难将数据从api发布到项目终点错误405方法被拒绝

问题描述

我正尝试将一些数据从openweathermap api发布到项目终点,因为我打算使用这些数据来更改用户界面。似乎一切正常,除非将数据发布到端点?我在这里想念什么? 我在这里使用Promise和一些异步功能...

app.js:

const baseUrl = "http://api.openweathermap.org/data/2.5/weather?zip=";
const apiKey = ",us&appid=858fd174cf6644c557a7f67c600cb59d";
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth() + "." + d.getDate() + "." + d.getFullYear();

document.getElementById("generate").addEventListener("click",() => {
  const valueOfZip = document.getElementById("zipCode").value;
  const valueOfFeelings = document.getElementById("feelings").value;
  getData(baseUrl,valueOfZip,apiKey).then((data) => {
    postData("/add",{
      humidaty: data.main.humidaty,cloudiness: data.weather.description,sunrise: convertTime(data.sys.sunrise),// this function to convert the time only.
      sunset: convertTime(data.sys.sunset),windSpeed: data.wind.speed,feelings: valueOfFeelings,});
  });
});

const getData = async (baseURL,_value,key) => {
  const res = await fetch(baseURL + _value + key);
  try {
    const data = await res.json();
    console.log(data);
    return data;
  } catch (error) {
    console.log("error",error);
    // appropriately handle the error
  }
};

const postData = async (url = "",data = {}) => {
  const response = await fetch(url,{
    method: "POST",credentials: "same-origin",headers: {
      "Content-Type": "application/json",},body: JSON.stringify(data),});

  try {
    const newData = await response.json();
    return newData;
  } catch (error) {
    console.log("error",error);
  }
};


server.js:

// Setup empty JS object to act as endpoint for all routes
let projectData = [];

// Require Express to run server and routes
const express = require("express");
// Start up an instance of app
const app = express();
/* Middleware*/
const bodyParser = require("body-parser");
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors for cross origin allowance
const cors = require("cors");
app.use(cors());
// Initialize the main project folder
app.use(express.static("website"));

// Setup Server
const port = 8000;
const server = app.listen(port,() => {
  console.log("Server is running...");
  console.log("Used port: " + port);
});

app.get("/getData",(req,res) => {
  res.send(projectData);
});

app.post("/add",res) => {
  newData = {
    humidaty: req.body.humidaty,cloudiness: req.body.cloudiness,sunrise: req.body.sunrise,sunset: req.body.sunset,windSpeed: req.body.windspeed,feelings: req.body.feelings,};

  projectData.push(newData);
  console.log(projectData);
});

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)