Используйте метод POST для сохранения (сохранения) данных в файле JSON на сервере. - PullRequest
1 голос
/ 13 февраля 2020

Я хочу сохранить данные в файл stati c JSON, сидящий на моем сервере, с помощью запроса Fetch POST.

Возможно ли это сделать? Если да, то любые советы или рекомендации будут признательны

Мой Javascript код, чтобы попытаться сохранить данные в мой файл JSON.

fetch('link-data.json', {    
method:'POST',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-type':'application/json'
        },
        body:JSON.stringify({
            id:3,
            title:"website_title",
            url:"www.example.com",
            description:"Hi_there_im_a_description"
             })
        })
        .then((res) => res.json())
        .then((data) => console.log(data))

Мой JSON файл Я хочу сохранить данные к.

[
{
  "id": 0,
  "title": "Twitter. It's what's happening.",
  "url": "https://twitter.com/?lang=en",
  "description": "From breaking news and entertainment to sports and politics, get the full story with all the live commentary."
},
{
  "id": 1,
  "title": "Netflix - Watch TV Shows Online, Watch Movies Online",
  "url": "https://www.netflix.com/",
    "description": "Watch Netflix movies & TV shows online or stream right to your smart TV, game console, PC, Mac, mobile, tablet and more."
    },
    {
      "id": 2,
      "title": "Facebook - Log In or Sign Up",
      "url": "https://www.facebook.com/",
      "description": "Create an account or log into Facebook. Connect with friends, family and other people you know. Share photos and videos, send messages and get updates."
    }
]

1 Ответ

1 голос
/ 14 февраля 2020

Да, вы можете. Если вы используете Node.Js, есть простой способ добиться этого. Допустим, вы делаете запрос POST на website.com/saveFile. Тогда код будет выглядеть примерно так:

const url = require('url')
const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res)=>{
    switch(url.parse(req.url).pathname){
        case '/saveFile':
            let body = ''

            //saving post data into variable body
            req.on('data', chunk=>{
                 body+= chunk.toString()
            })
            req.on('end', ()=>{
                //reading json file
                fs.readFile(__dirname+'/link-data.json', (err, data)=>{
                    if (err) throw err
                    dataJson = JSON.parse(data) //object with your link-data.json file
                    postData = JSON.parse(body) //postData is the variable containing your data coming from the client.
                    dataJson.push(postData)//adds the data into the json file.

                    //Update file
                    fs.writeFile(__dirname+'/link-data.json', JSON.stringify(dataJson), (err)=>{
                      if(err) console.log(err)
                      res.end()
                    })
                })
            })
    }
})

server.listen(5000, ()=>{
    console.log('Server listening at port 5000!')
})

Для этого нужно открыть файл JSON с помощью внутреннего модуля File System (FS) Node.Js, проанализировав его с объектом Javascript и добавление данных в массив. Затем файл обновляется (с помощью функции fs.writeFile ()).

Вы также можете отправить ответ JSON, чтобы сообщить, что все прошло как запланировано:

res.end(JSON.stringify({"status": "success"}))

...