创建基本的服务器
const express = require('express');
const cors = require('cors');
const app = express();
app.use(express.urlencoded( {extended: false} ))
app.use(cors())
const router = require("./apiRouter.js")
app.use("/api",router)
app.listen(80,()=>{
console.log("http://127.0.0.1");
});
创建 API 路由模块
const express = require('express');
const router = express.Router();
router.get("/get",(req,res)=>{
const query = req.query;
res.send({
status: 0,
msg: "GET 请求成功!",
data: query,
})
})
router.post("/post",(req,res)=>{
let body = req.body;
res.send({
status: 0,
msg: "POST 请求成功!",
data: body,
})
})
router.delete("/delete",(req,res)=>{
res.send({
status: 0,
msg: "DELETE 请求成功!",
})
})
module.exports = router;
调试接口
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<button id="btnGET">GET</button>
<button id="btnPOST">POST</button>
<button id="btnDelete">DELETE</button>
<button id="btnJSONP">JSONP</button>
<script>
$(function(){
$('#btnGET').on('click', function () {
$.ajax({
type: 'GET',
url: 'http://127.0.0.1/api/get',
data: { name: 'GET', age: 20 },
success: function (res) {
console.log(res)
},
})
})
$('#btnPOST').on('click', function () {
$.ajax({
type: 'POST',
url: 'http://127.0.0.1/api/post',
data: { name: 'POST', age: 20 },
success: function (res) {
console.log(res)
},
})
})
$('#btnDelete').on('click', function () {
$.ajax({
type: 'DELETE',
url: 'http://127.0.0.1/api/delete',
data: { name: 'POST', age: 20 },
success: function (res) {
console.log(res)
},
})
})
})
</script>
</body>
</html>