【nodejs】vue前端+nodejs后端通訊最簡單demo


效果演示

本示例效果如下:前端是一個登陸表單,信息提交給后端,后端收到后給前端反饋信息。

 

技術架構

前端 vue + axios + wepack
后端 nodejs + express

前端部分

安裝部署

前端安裝vue,方式多種,本文使用vue-cli3 + vue ui圖形化安裝,具體請百度,命令如下:
安裝 vue-cli3:npm i @vue/cli -g
vue圖形化安裝:vue ui
安裝 axios 用於和后端通訊:npm i axios -s

前端代碼

然后我們打開“App.vue”,把代碼改成如下:
建立了一個登陸表單,提交按鈕點擊后向“http://127.0.0.1:3000/login”這個后端地址post表單數據。

<template>
    <div>
        <form method="post">
            賬號 :
            <input type="text" id="name" />
            <br /><br />
            密碼 :
            <input type="text" id="pwd" />
            <br /><br />
            <input type="button" value="提交" @click="submit">
        </form>
    </div>
</template>

<script>
    import axios from 'axios'
    export default {
        methods: {
            submit() {
                var name = document.getElementById("name").value;
                var pwd = document.getElementById("pwd").value;
                if (name == "" || pwd == "") {
                    alert("帳號和密碼不能為空")
                } else {
                    //向服務器提交數據
                    axios.post('http://127.0.0.1:3000/login', {
                            name: name,
                            pwd: pwd
                        })
                        .then(function(response) {
                            //成功時服務器返回 response 數據
                            alert(response.data)
                        })
                        .catch(function(error) {
                            console.log(error);
                        });
                }
            }
        },
    }
</script>

運行前端終端

此時我們運行終端,在終端輸入npm run serve,運行后打開http://localhost:8080/ 能看到我們的前端頁面效果。

后端部分

安裝部署

后端需要安裝 express 和 body-parser(用於解析前端post過來的數據),順便安裝 nodemon(用於后端熱更新)
安裝 express:npm i express -s
安裝 body-parser: npm i body-parser -s
安裝 nodemon npm i nodemon -d

后端代碼:

安裝完后,在src目錄下建立serve.js,然后輸入如下代碼,代碼功能請看注釋,注意跨域部分:

var express             = require('express');
var app                 = express();
var bodyParse           = require('body-parser')

//增加頭部信息解決跨域問題
app.all('*', function (req, res, next){
    res.header("Access-Control-Allow-Origin", "http://localhost:8080");//允許源訪問,本利前端訪問路徑為“http://localhost:8080”
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("X-Powered-By", ' 3.2.1');
    next();
});

//使用bodyParse解釋前端提交數據
app.use(bodyParse.urlencoded({extended:true})) ;
app.use(bodyParse.json());

// 處理根目錄的get請求
app.get('/',function(req,res){
}) ;

// 處理/login請求
app.post('/login',function(req,res){
    //獲取登錄名稱和密碼
    name=req.body.name ;
    pwd=req.body.pwd;
    //向前台反饋信息
    res.status(200).send(
        "后台反饋信息:登錄帳號:"+name+" | 登錄密碼:"+pwd
      ) ;
});

// 監聽3000端口
var server=app.listen(3000);

console.log("服務器已運行");
console.log("監聽網址為:http://127.0.0.1:3000/");

運行后端終端

此時我們新建一個終端,運行如下代碼:
進入src目錄 cd src
運行serve.js nodemon serve.js

運行效果如下,本文以vscode為例:

 

此時后端服務已經建立起來,然后我們訪問前端入口 http://localhost:8080/,就可以看到“演示效果”了。

轉自:https://blog.csdn.net/iamlujingtao/article/details/103948399


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM