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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值