This article is for the author to learn Node notes, to be perfected, welcome to exchange and learn together.
Table of contents
1. Preparation
1. Create a basic server
//导入express
const express = require('express')
//创建web服务器
const app = express()
//启动服务器
app.listen(8083,()=>{
console.log('express server running at http://127.0.0.1:8083')
})
2. Create an API routing module
const express = require('express')
const router = express.Router()
//在这里挂载对应的路由
module.exports = router
3. Import the created routing module into the server file
const express = require('express')
const router = require('./8.apiRouter')
const app = express()
app.use('/api', router)
app.listen(8083, () => {
console.log('http://127.0.0.1:8083');
})
2. Basic use
1. Write the GET interface
Write the following code in the routing file:
//在这里挂载对应的路由
router.get('/get',(req,res)=>{
//获取到客户端通过查询字符串,发送到服务器的数据
const query = req.query;
//调用res.send()方法,把数据响应给客户端
res.send({
status:0,//0表示成功,1表示失败
message:"GET请求成功",//状态的描述
data:query//需要响应的数据
})
})
The result of using Post man request is as follows:
2. Write the POST interface
If you want to obtain request body data in URL-encoded format, you must configure middleware for parsing form data in the server js file:
//配置解析表单数据的中间件
app.use(express.urlencoded({
extended:false}))
Write the following code in the routing file:
router.post('/post', (req, res) => {
//通过req.body获取请求体中包含的url-encoded格式的数据
const body = req.body
res.send({
status: 0,//0表示成功,1表示失败
message: "POST请求成功",//状态的描述
data: body//需要响应的数据
})
})
The result of using Post man request is as follows:
3. All codes
1. Server file
const express = require('express')
const router = require('./8.apiRouter')
const app = express()
//配置解析表单数据的中间件
app.use(express.urlencoded({
extended:false}))
app.use('/api', router)
app.listen(8083, () => {
console.log('http://127.0.0.1:8083');
})
2. Routing file
const express = require('express')
const router = express.Router()
router.get('/get', (req, res) => {
const query = req.query
res.send({
status: 0,//0表示成功,1表示失败
message: "GET请求成功",//状态的描述
data: query//需要响应的数据
})
})
router.post('/post', (req, res) => {
//通过req.body获取请求体中包含的url-encoded格式的数据
const body = req.body
res.send({
status: 0,//0表示成功,1表示失败
message: "POST请求成功",//状态的描述
data: body//需要响应的数据
})
})
module.exports = router
4. Cross-domain issues
1. Use CORS middleware to solve cross-domain problems
CORS is a third-party middleware of Express. By installing and configuring CORS middleware, you can easily solve cross-domain problems.
The steps to use are as follows:
- Run npm i cors to install middleware
- Import middleware with const cors = require('cors')
- Called before routingapp.use(cors()) configure middleware
2. CORS response header Access-Control-Allow-Origin
A field can be carried in the response header Access-Control-Allow-Origin
, and its syntax is as follows:
Access-Control-Allow-Origin: <origin> | *
Among them, the value of the origin parameter specifies theExternal domain URLs that are allowed to access this resource
For example, the following field values only allow requests from https://www.baidu.com:
res.setHeader('Access-Control-Allow-Origin','https://www.baidu.com')
If the specified field value is a wildcard *
, it means that requests from any domain are allowed:
res.setHeader('Access-Control-Allow-Origin','*')
3. CORS response header Access-Control-Allow-Headers
By default, CORS only supports the client sending the following 9 request headers to the server:
Accept, Accept-Language, Content-Language, DPR, Downlink, Save-Data, Viewport-Width, Width, Content-Type (values are limited to text /plain multipart/form-data application/x-www-form-urlencoded one of the three)
If the client sends an additional request header to the server, it needs to declare the additional request header through this response header on the server side, otherwise the request will fail this time
Instructions:
res.setHeader('Access-Control-Allow-Headers','Content-Type,X-Custom-Header')
4. CORS response header Access-Control-Allow-Methods
By default, CORS only supports clients to initiate GET, POST, HEAD requests.
If the client wants to PUT、DELETE
request server resources through other methods, it needs to specify the HTTP method allowed by the actual request through Access-Control-Allow-Methods on the server side
.
//只允许使用POST、GET、DELETE、HEAD请求方法
res.setHeader('Access-Control-Allow-Methods','POST','GET','DELETE','HEAD')
//允许所有的HTTP请求方法
res.setHeader('Access-Control-Allow-Methods','*')