当前位置:网站首页>Use koa to mock data and set cross domain issues
Use koa to mock data and set cross domain issues
2022-06-13 01:25:00 【Durian is not delicious】
brief introduction
Installation and use process
install
npm i -S koa
npm i -S koa-router
npm i -S koa-bodyparser
Import the following methods ;
const Koa = require('koa');
const router = require('koa-router')();
// post request , Request body required , At this time, you need to install koa-bodyparser, It can be parsed from body The data transmitted from it
const bodyparser = require('koa-bodyparser');
const fs = require('fs');// fs The file system is nodejs Built in , No installation required .
app.use(bodyparser())
Print log
// When the service period is accessed , Print out the request type and the requested url;
app.use(async (ctx, next) => {
console.log(`${
ctx.request.method} ${
ctx.request.url}`);
await next();
});
Interface
// post request
router.post('/api/postUser', async (ctx, next) => {
// ctx.request.body Requested parameters
const {
username, password } = ctx.request.body
if (!username || !password) {
ctx.response.body = {
Msg: " User name or password cannot be empty ", ResultCode: 0}
return;
}
let ret = null
try {
ret = await fs.readFileSync('./user.json')
ret = JSON.parse(ret.toString())
} catch (error) {
ret = []
}
ret.push({
username, password })
ctx.response.body = {
Msg: " Registered successfully ", ResultCode: 1 }
try {
fs.writeFileSync('./user.json', JSON.stringify(ret))
ctx.response.body = {
Msg: `${
username} Registered successfully `, ResultCode: 1}
} catch (err) {
if (err) ctx.response.body = {
Msg: " Registration failed , Please re submit ", ResultCode: 0}
}
});
// get request
router.get('/api/getUser', async (ctx, next) => {
ctx.response.body = {
name: ' Zhang San ',
phone: '15111111111'
}
});
Add router Middleware , And setting the service period host And port
app.use(router.routes());
const host = '131.122.2.55';
const port = '2255';
app.listen(port, host, () => {
console.log(`http://${
host}:${
port}`);
});
Call in project :
axios.post('http://131.122.2.55:2255/api/postUser',{
username: " Zhang San 12"}).then(ret => {
console.log(ret);
})
axios.get('http://131.122.2.55:2255/api/getUser').then(ret => {
console.log(ret);
})
The result is shown in Fig. 
To solve the cross domain
install npm i -S koa2-cors
const cors = require('koa2-cors');
app.use(
cors({
origin: function (ctx) {
// Set to allow requests from the specified domain name
return '*';
// if (ctx.url === '/choose-city') { return '*'; // Allow requests from all domain names }
// return 'http://localhost:8080'; // Only http://localhost:8080 This domain name request
},
maxAge: 5, // Specify the validity period of this pre inspection request , The unit is in seconds .
credentials: true, // Is it allowed to send Cookie
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Set the allowed HTTP Request method '
allowHeaders: ['Content-Type', 'Authorization', 'Accept'], // Set all header information fields supported by the server
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] // Set get other custom fields
})
);
Run again node mock.js The results are as follows 
Complete code The results are shown in the figure below , The new data is stored locally user.json In the document
Please stamp the complete code

边栏推荐
- Five classic articles worth reading
- 707. design linked list
- Sliding window summary of TCP connections
- Leetcode-13- Roman numeral to integer (simple)
- Crypto JS reports uglifyjs error
- Leetcode question brushing 02 linked list operation
- ES6解构赋值
- Database query user mailbox
- 304. Merge two ordered arrays
- FSOs forest simulation optimization model learning notes
猜你喜欢

Mathematical knowledge arrangement: extremum & maximum, stagnation point, Lagrange multiplier

使用Pygame创建一个简单游戏界面

Go JWT learning summary

Simple operation of MySQL database
![[leetcode] valid phone number Bash](/img/f8/cecb74f9d8f7c589e62e3a9a874f82.jpg)
[leetcode] valid phone number Bash

4K sea bottom and water surface fabrication method and ocean bump displacement texture Download

spiral matrix visit Search a 2D Matrix

Jenkins continuous integration operation

【斯坦福計網CS144項目】Lab1: StreamReassembler

How does Apple add QQ email?
随机推荐
What kind of experience is it to be a software test engineer in a state-owned enterprise: every day is like a war
C language implementation of the classic eight queens problem
Most elements leetcode
Binary tree traversal - recursive and iterative templates
Golang learning essay
How to solve the problem of database?
使用Pygame创建一个简单游戏界面
Leetcode find duplicates
Differences among bio, NiO and AIO
How to solve the problems when using TV focusable to package APK in uni app
Plusieurs catégories de tests logiciels sont claires à première vue
Redis usage optimization summary learning
Stmarl: a spatio temporal multi agentreinforcement learning approach for cooperative traffic
How to choose stocks? Which indicator strategy is reliable? Quantitative analysis and comparison of DBCD, ROC, vroc, Cr and psy index strategy income
Docker install MySQL
Summary of various installation methods of Lab View
Add default right-click menu
5G工业网关在煤矿行业的应用优势
Leetcode question brushing 03 stack
Deadlock problem summary