如何解决我很难将数据从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);
});
解决方法
我认为您没有使用正确的服务器URL。
postData("/add",{...
应该不是“ localhost:8000 / add”吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。