get和post请求

get请求

首先创建一个文件夹,在创建index.js文件文件中

​
// 引入express框架
const express = require('express');
// 创建网站服务器
const app = express();
// 监听端口
app.listen(3000);
console.log('网站服务器启动成功');

​

其次在创建一文件为src,在src宅在创建一个js文件

 在01.js文件中

const express = require('express')
const router = express.Router()
//挂载路由
router.get('/get',(req,res)=>{
  //req.query获取客户端查询字符发送数据
  const query = req.query
  //res.send()向客户端响应结果
  res.send({
    status:0,
    msg:'get请求成功',
    data:query
  })
})
//暴露
module.exports = router

在回到index.js中添加

然后再src中创建一个html文件

​
//导入路由模块
const router =require('./src/01')
//注册app
app.use('/api',router)
app.get('/get',(req,res) => {
    res.send(req.query);
})

​

再html中引入jquery文件

<script src="https://cdn.staticfile.org/jquery/3.6.1/jquery.min.map"></script>

写上两个按钮

​
 <div><button id="btn1">get</button></div>
 <div><button id="btn2">post</button></div>

​

再写上调取接口的方法

​
 $(function(){
        $('#btn1').on('click',function(){
            $.ajax({
                type:'get',
                URL:'http://127.0.0.1:40404/api/get',
                data:{},
                success:function(res){
                    console.log(res)
                }
            })
        })

​

post

再以上基础上面再01.js文件中添加一个post接口

//定义post 接口
router.post('/post',(req,res)=>{
  //req.body获取客户端查询字符发送数据
  const body = req.body
  //res.send()向客户端响应结果
  res.send({
    status:0,
    msg:'pos请求成功',
    data:body
  })
})

对应html代码

$('#btn2').on('click',function(){
            $.ajax({
                type:'post',
                URL:'http://127.0.0.1:40404/api/post',
                data:{},
                success:function(res){
                    console.log(res)
                }
            })
        })

再index.js中

​ app.post('/post',(req,res)=>{
// 设置响应头设置允许跨域
    res.setHeader('Access-Control-Allow-Origin','*')
    //因为是post,所以使用body
    var data = req.body;
})

​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值