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;
})