1. 程式人生 > >Nodejs入門基礎(使用express模組通過JSON(GET、POST)提交方式獲取或返回值)

Nodejs入門基礎(使用express模組通過JSON(GET、POST)提交方式獲取或返回值)

前端通過ajax get或則post方式提交資料到後臺,後臺傳遞資料到前臺互相呼叫

getjson.html:
 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>postjson提交</title>
    <!--引入jquery包-->
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        /*用於按鈕觸發ajax*/
        function sub(){
           $.ajax({
               /*ajax屬性,get方式可以直接在url進行拼接*/
               type:"GET",
               /*傳遞過去的值*/
               url:"http://localhost:3000?name=jw&&age=18",
               success:function(res){
                   /*輸出返回的值*/
                   console.log(res);
               }
           })
        }
    </script>
</head>
<body>
    <button onclick="sub()">getjson請求</button>
</body>
</html>

getjson.js

 

var express=require("express");//匯入express
var app = express();//例項化

app.use(express.static("static"));//靜態內容

app.all('*',function(req,res,next){//跨域問題
    res.setHeader("Access-Control-Allow-Origin", "*");
    next();
});

app.get("/",function(req,res){
    console.log(req.query);//獲取前端ajax傳遞過來的資訊並輸出
    res.send({//返回資訊給前端
        "msg":"返回資料"
    })
}).listen(3000);



postjson.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>postjson提交</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        function bus() {
            $.ajax({
                type:"POST",
                url:"http://localhost:3000/post",
                data:{
                    name:"jw",
                    age:18,
                },
                success:function(res){
                    console.log(res);
                }
            })
        }
    </script>
</head>
<body>
    <button onclick="bus()">postjson提交</button>
</body>
</html>

postjson.js
 

var express = require("express");
var app = express();//
var bodyParser = require("body-parser");//使用外掛,用於解析/post

app.use(express.static("static"));//載入專案靜態內容

app.all('*', function (req, res, next) {//設定跨域問題
    res.setHeader("Access-Control-Allow-Origin", "*");
    next();
});

app.use(bodyParser.urlencoded({extended: false}));//解析字元

app.post("/post", function (req, res) {
    console.log(req.body);//獲取前端ajax提交的資料
    res.send({
        "msg":"post",
        "code":1
    })
}).listen(3000);