首页 > 解决方案 > 我很难将数据从 api 发布到项目端点(错误 405 方法被拒绝。)

问题描述

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

应用程序.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", (req, 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);
});

标签: javascriptnode.jsexpressroutes

解决方案


我认为您没有使用正确的服务器 URL。

postData("/add", {...

不应该是 "localhost:8000/add" 吗?


推荐阅读