1.創建基本的服務器
創建一個index.js檔案
const express=require('express')
const app=express()
app.listen(3000,()=>{
console.log('running......')
})
2.創建API路由模塊
新建一個router.js檔案
const express = require('express')
const router=express.router()
//在這里掛載路由
module.exports=router
3.在 index.js中匯入router模塊
const router=require('./router.js')
//把路由模塊,注冊到app上
app.use('./api',router)
4.撰寫 get 請求
const express = require('express')
const router=express.router()
//在這里掛載路由
router.get('/',(req,res)=>{
//通過req.query獲取客戶端通過查詢字串發送到服務器的資料
const query=req.query;
//呼叫res.send()方法,向客戶端回應處理的結果
res.send({
status:0,
msg:'GET 請求成功',
data:query
})
})
module.exports=router
5. 撰寫 post 請求
注意:如果要獲取 URL-encoded 格式的請求體資料,必須配置中間件 app.use(express.urlencoded({ extended: false }))
// 配置決議表單資料的中間件
app.use(express.urlencoded({ extended: false }))
router.post('/',(req,res)=>{
// 通過 req.body 獲取請求題中包含的 url-encoded 格式的資料
const query=req.query;
//呼叫res.send()方法,向客戶端回應處理的結果
res.send({
status:0,
msg:'POST 請求成功',
data:query
})
})
6. 創建一個index.html檔案
用來測驗介面
<!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.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>
<body>
<button class="btn1">get</button>
<button class="btn2">post</button>
<script>
$(function () {
$('.btn1').click(function () {
$.ajax({
url: 'http://127.0.0.1:3000/api/book?name=tom&age=10',
success: function (data) {
console.log(data)
}
})
})
$('.btn2').click(function () {
$.ajax({
url: 'http://127.0.0.1:3000/api/book',
method: 'post',
data: {
name: '雪中悍刀行',
author: '烽火戲諸侯'
},
success: function (data) {
console.log(data)
}
})
})
})
</script>
</body>
</html>
我們在瀏覽器中打開或看到報錯:

這是介面的跨域問題
-
到目前為止,我們撰寫的
GET和POST介面,存在一個很嚴重的問題:不支持跨域請求 -
解決介面跨域問題的方案主要有兩種
- CORS (主流的解決方案,推薦使用)
- JSONP (有缺陷的解決方案:只支持 GET 請求)
7. 使用 cors 中間件解決跨域問題
cors 是 Express 的一個第三方中間件,通過安裝和配置 cors 中間件,可以很方便地解決跨域問題
使用步驟:
安裝中間件: npm install cors
匯入中間件: const cors = require('cors')
配置中間件: 在路由之前呼叫app.use(cors())
// 匯入中間件
const cors = require('cors')
// 配置中間件
app.use(cors())
配置 cors 插件后:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/308859.html
標籤:其他
上一篇:express 自定義中間件
