Using Express to build Node.js server

Keywords: Vue axios JSON npm

Express: a fast, open and simple web development framework based on Node.js platform.

Explain

Installation:
  • Third party npm is used here
  • Install express
npm install express
To build Express:
  • New JS file: server.js
//1. guide pack
const express = require('express');
const bodyParser = require('body-parser')

//2. create App
const app = express();

// parse application/x-www-form-urlencoded only supports usernname = Lisi & password = Lisi
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json only supports "{username:'lisi',password:'lisi'}"
app.use(bodyParser.json())


//Server side settings allow cross domain
app.all('/*',(req,res,next)=>{
    //Tell the browser some extra information
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("X-Powered-By",' 3.2.1')
    res.setHeader("Content-Type", "application/json;charset=utf-8");

    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
    res.setHeader("Access-Control-Expose-Headers", "*");

    next();
})

//3. Routing

//GET login request processing
app.get('/api/login',(req,res)=>{
    const result = {status:1,message:"Login successfully"}
    //      /login?username=zhangsan&password=123
    if (req.query.username=='zhangsan' && req.query.password=='123'){

    }else{
        result.status = 0;
        result.message = "User name or password failed"
    }
    res.setHeader("Content-Type","text/json;charset=utf-8");
    res.json(result);
})

//POST login request processing
app.post('/postLogin',(req,res)=>{
    const result = {status:1,message:"Login successfully"}
    if (req.body.username=='lisi' && req.body.password=='lisi'){

    }else{
        result.status = 0;
        result.message = "User name or password failed"
    }
    res.setHeader("Content-Type","text/json;charset=utf-8");
    res.json(result);
})

//4. boot
app.listen(3000,"127.0.0.1", function(){
    console.log("start success");
});
Test Express
  • I use vscode, select server.js file, right click: select open in terminal
  • Start the application with the following command: node server.js
  • If successful: output start success
Call server to demonstrate two types
preparation:
  • Import files
    <script src="https://cdn.bootcss.com/vue/2.5.13/vue.js"></script>
    <script src="https://cdn.bootcss.com/vue-resource/1.3.4/vue-resource.js"></script>

First: Vue resource

// html code
<div id="app">
    <button @click="jsonp()">Send out JSONP request</button>
</div>
Use get request
<script>

    // console.log(window)
    Vue.use(VueResource) //Vue.propertype.$http = VueResource

    const vm = new Vue({
        el:'#app',
        methods:{
            getLogin(){
                //1.url
                const url = "http://IP address: 3000 / API / login? Username = Lisi & password = 123“

                this.$http.get(url).then(function(response){
                    console.log(response.body)
                },function(err){
                    console.log(err)
                })
            }
        }
    })
</script>
Use post request
<script>
    const vm = new Vue({
        el:'#app',
        methods:{
            postLogin(){
                //1.url
                const url = "http://IP address: 3000/postLogin“

                //username=lisi&password=lisi
                //Request header content type: application / x-www-form-urlencoded
                this.$http.post(url,{username:'lisi',password:'lisi'},{emulateJSON:true}).then(response=>{
                    console.log(response.body)
                },err=>{
                    console.log(err)
                })
            }
        }
    })
</script>
Cross domain request using jsonp
<script> 
    new Vue({
        el:'#app',
        methods: {
            jsonp() {
                const url ="https://api.douban.com/v2/movie/in_theaters";
                this.$http.jsonp(url).then((response) => {
                    console.log(response.body);
                }, (err) =>{
                    console.log(err)
                })
            }
        }
    })
</script>

Second: axios

  • Import files
 <script src="https://cdn.bootcss.com/vue/2.5.13/vue.js"></script>
 <!-- After importing, it is equivalent to jQuery -->
 <script src="https://cdn.bootcss.com/axios/0.17.1/axios.js"></script>
Use get request
<script>
    const vm = new Vue({
        el:'#app',
        methods:{
            getLogin(){
                //1.url
                const url = "http://IP address: 3000 / API / login? Username = Zhangsan & password = 123“
                axios.get(url).then(response=>{
                    console.log(response.data)
                },err=>{
                    console.log(err)
                })
            }
        }
    })
</script>
Use post request
<script>
    const vm = new Vue({
        el:'#app',
        methods:{
            postLogin(){
                //1.url
                const url = "http://IP address: 3000/postLogin“

                // axios.post(url,"username=lisi&password=lisi").then(response=>{
                //     console.log(response.data)
                // },err=>{
                //     console.log(err)
                // })

                //In this way, it will eventually submit the string in json format
                axios.post(url,{username:'lisi',password:'lisi'}).then(response=>{
                    console.log(response.data)
                },err=>{
                    console.log(err)
                })
            }
        }
    })
</script>

The difference between Vue resource and axios

1. vue resource is based on vue and can only be used in vue
 2. axios is not based on Vue and can be used in other frameworks
 3. Vue resource supports jsonp, axios does not
 4. Vue resource is not supported in node, axios supports

Posted by mattyj10 on Wed, 01 Apr 2020 11:04:38 -0700