简体   繁体   中英

send data to json file with javascript fetch api

i have one empty json file. I want to add json data to my json file when button is clicked. but it gives error 405. how can I do?

error:

POST net::ERR_ABORTED 405 (Method Not Allowed)

code:

var data={
                        method:"POST",
                        body:{
                            userId:1,
                            title:"sample title",
                            body:"sample body"
                        },
                        headers:new Headers({
                            'content-type':'application/json',
                            'dataType': 'json'
                        })
                    }

           

                    fetch("anaveri.json",data).
                    then(res=>{
                        console.log(res);
                    }).
                    catch(error=>{
                        console.log(error);
                    });

The browser isn't able to directly write data to the server's file system.

It would be a horrible security problem if it could. Google's homepage would get overwritten with some different bit of trolling every few seconds!

The browser can send an HTTP request to a URL. The server then needs to use server side programming to process that request.

You need to pick a programming language that your server supports (or change servers to one that supports your server-side language of choice) and write a webservice that takes the data from the request and stores it.

You could have it write directly to a JSON file, but that risks "fun" problems with concurrent writes so it is more typical to store the data in a database and have another webservice generate the JSON on demand.

You should consider adding some sort of tests (eg password authentication and data validation) to control who can insert new data and what sort of data they can insert to avoid the aforementioned vandalism problem.

Client-side scripting isn't allowed to change files on the server or the local file system for security reasons. Depending on what you're trying to achive, you need to do one of these things:

  1. Send your data to your server via POST and your server does the saving
  2. Create the file contents blob and download it
  3. Use the browser's FileSystem API instead of the client one's

405 (Method Not Allowed) means that the resource you're querying (in this case, your json file) does not implement the method you're trying to use on it. In order to add information to your json file, you need to have some sort of a backend logic that implements a RESTful API, so that you can issue requests using JavaScript - you can't just do it with JavaScript alone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM