Показать сообщение отдельно
  #2 (permalink)  
Старый 26.10.2018, 15:07
Аватар для SuperZen
Профессор
Отправить личное сообщение для SuperZen Посмотреть профиль Найти все сообщения от SuperZen
 
Регистрация: 08.11.2017
Сообщений: 641

Не знаю зачем..., но вот:

index.js
const express = require('express')
const app = express()
const path = require('path')
const fs = require('fs')
const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'))
})

app.get('/data', (req, res) => {
  fs.readFile(path.join(__dirname, 'data.json'), 'utf8', (error, data) => {
    if (error) res.json({ status: 'error' })
    res.json(JSON.parse(data))
  })
})

app.post('/save', (req, res) => {
  fs.readFile(path.join(__dirname, 'data.json'), 'utf8', (error, data) => {
    if (error) res.json({ status: 'error' })
    const nextData = JSON.parse(data)
    nextData.push({ id: nextData.length + 1, title: req.body.title })
    fs.writeFile(path.join(__dirname, 'data.json'), JSON.stringify(nextData), 'utf8', (error) => {
      if (error) res.json({ status: 'error' })
      res.json(nextData)
    })
  })
})

app.listen(3000, () => {
  console.log('started on port 3000')
})


data.json
[
  {
    "id": 1,
    "title": "русские буквы"
  }
]


index.html
<div id="result"></div>
<input id="text" type="text" />
<input id="load" type="button" value="load" />
<input id="save" type="button" value="save" />
<script>
  const client = (function () {
    return {
      getData() {
        fetch('/data')
          .then(r => r.json())
          .then(r => document.getElementById('result').innerText = JSON.stringify(r))
      },
      save() {
        fetch('/save', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ title: document.getElementById('text').value })
        })
          .then(r => r.json())
          .then(r => document.getElementById('result').innerText = JSON.stringify(r))
      }
    }
  })()

  document.getElementById('save').addEventListener('click', function () {
    client.save()
  })

  document.getElementById('load').addEventListener('click', function () {
    client.getData()
  })
</script>


package.json
{
  "name": "tests",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.4"
  }
}


yarn install или npm install
node index.js

http://localhost:3000
Ответить с цитированием