node Notes - Writing of json Files

What we did was a little demo.
The general contents are as follows:
1. Front End of Vue Framework Writing
2.axios call interface
3. Write json through interface
4. access to all computers in the LAN.

First you need to install something
Front end is

npm install axios

Back-end installation of express framework

npm install express --save
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save

Front-end page:

    write() {
      this.axios
        .get(`http:// Your ip address: 8081/? Name =${this.name} & score =${this.score} `
        .then(res => {
          console.log("res --->", res);
        })
        .catch(err => {
          console.log("err --->", err);
        });
    }

The content is relatively simple, so write a write method.
Call the interface through axios and pass parameters
Fill in your IP address because you want to access it in the LAN, which is equivalent to the local machine is a server. Other people in the LAN fill in the name and score will access the 8081 port of the local machine and write to the JSON file of the local machine.

Api.js

var fun = require('./fun')
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.all("*", function (req, res, next) {
    //Setting a domain name that allows cross-domain,* means allowing any domain name to cross-domain
    res.header("Access-Control-Allow-Origin", "*");
    //Permissible header type
    res.header("Access-Control-Allow-Headers", "content-type");
    //Cross-domain permissible request mode 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //Let options try to end the request quickly
    else
        next();
})
// Create application/x-www-form-urlencoded encoding analysis
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use('/public', express.static('public'));

app.get('/', function (req, res) {
    fun.writeJson(req.query)
})

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("<----------  The service has been started  ---------->")
    console.log("<---------  Service port:8081 --------->")
})

Fun is another function that provides JSON writes. The main function of this Api is to set up cross-domain and call interfaces. You can see that app.get calls the fun. write Json method.

fun.js

var fs = require('fs');
//In real development, id must be randomly generated and not duplicated. In the next article, how to generate random number that can't be duplicated, let's simulate the false data.
//Write to json file option
function writeJson(params) {
    //Now read out the json file
    fs.readFile('../src/assets/score.json', function (err, data) {
        if (err) {
            return console.error(err);
        }
        var person = data.toString();//Converting binary data to strings
        person = JSON.parse(person);//Converting strings to json objects
        person.data.push(params);//push the incoming object into the array object
        person.total = person.data.length;//Define the total number of entries to lay the foundation for future paging
        var str = JSON.stringify(person);//Because the write file of nodejs only knows strings or binary numbers, it converts json objects into strings and rewrites them into json files.
        fs.writeFile('../src/assets/score.json', str, function (err) {
            if (err) {
                console.error(err);
            }
            console.log('----------New success-------------');
        })
    })
}

module.exports = {
    writeJson
}

This is the way to write JSON files

If you want to access a computer in a LAN, you can access it.
Need to start the node service, mine is

node Api.js

In the previous section, you need to modify the config/index.js of the Vue project
Change the host localhost to its IP address
Then npm run dev
You can access pages in the LAN by accessing IP addresses.

Keywords: Front-end JSON npm axios Vue

Added by johne281 on Tue, 01 Oct 2019 23:30:20 +0300