[英]Why I can not use POST method to local json file using vanilla JavaScript fetch() API?
I can use the fetch API to do a HTTP POST request to an external JSON file, but it can't be done in the local JSON file. I can use the fetch API to do a HTTP POST request to an external JSON file, but it can't be done in the local JSON file.
class EasyHttp {
// http GET request
get(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((res) => resolve(res))
.catch((err) => reject(err));
});
}
// http POST request
post(url, data) {
return new Promise((resolve, reject) => {
fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => resolve(res))
.catch((err) => reject(err));
});
}
}
const http = new EasyHttp();
const newData = {
customerID: 1252123,
name: "Aditya Padukhan",
purchase: "Realme alubhaja pro",
productID: "158-hb-122",
};
http
.post("customers.json", newData)
.then((res) => res.json().then((data) => console.log(data)))
.catch((err) => console.log(err));
And I got an error:
我得到一个错误:
eassyhttp.js:16 POST http://127.0.0.1:5500/customers.json 405 (Method Not Allowed) (anonymous) @ eassyhttp.js:16 post @ eassyhttp.js:15 (anonymous) @ app.js:16 app.js:18
easyhttp.js:16 POST http://127.0.0.1:5500/customers.json 405(不允许的方法)(匿名)@easyhttp.js:16 发布@eassy app.jsm:16) app.js:18
SyntaxError: Unexpected end of JSON input at app.js:17
SyntaxError:app.js:17 处的 JSON 输入意外结束
The specification says :规范说:
The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics.
POST 方法请求目标资源根据资源自己的特定语义处理请求中包含的表示。
A static file has no means of processing the data that is posted. static 文件无法处理发布的数据。 JSON isn't a programming language.
JSON 不是编程语言。 There is nothing that can read the POST request and do anything with the data in it.
没有任何东西可以读取 POST 请求并对其中的数据执行任何操作。 Consequently, your web server is defaulting to saying "No, you can't POST here".
因此,您的 web 服务器默认为“不,您不能在此处发布”。
If you want to do something with the POST request, then you need to write some server side code that will do that something.如果你想对 POST 请求做一些事情,那么你需要编写一些服务器端代码来做这件事。 (If you want to just overwrite the existing JSON then you should probably be using PUT instead of POST too).
(如果您只想覆盖现有的 JSON 那么您可能也应该使用 PUT 而不是 POST)。 Note that allowing any HTTP request to change the data on the server is a bad idea and you really shouldn't allow it without some kind of authentication that limits requests to trusted people and/or logic to determine if the incoming data is "good".
请注意,允许任何 HTTP 请求更改服务器上的数据是一个坏主意,如果没有某种身份验证来限制对受信任的人的请求和/或确定传入数据是否“好”的逻辑,你真的不应该允许它.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.