当前位置:网站首页>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

边栏推荐
- Summary of various installation methods of Lab View
- Memory learning book reference
- #pragma comment(lib,“urlmon.lib“)
- Phaser3 load
- Deadlock problem summary
- Add default right-click menu
- leetcode. 541. reverse string II
- Introduction to common activation functions
- Leetcode question brushing 02 linked list operation
- Stmarl: a spatio temporal multi agentreinforcement learning approach for cooperative traffic
猜你喜欢

軟件測試的幾種分類,一看就明了

【斯坦福计网CS144项目】Lab1: StreamReassembler

【斯坦福計網CS144項目】Lab1: StreamReassembler
![[latex] insérer une image](/img/0b/3304aaa03d3fea3ebb93b0348c3131.png)
[latex] insérer une image

How to print infinite symbol in WPS

spiral matrix visit Search a 2D Matrix

Tangent and tangent plane

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

Set and array conversion, list, array

Leetcode question brushing 03 stack
随机推荐
Quick power explanation
[projet cs144 de Stanford Computing Network] lab1: Stream reassembler
Camera model_
生态聚合NFT来袭,Metaverse Ape引领Web 3.0元宇宙新范式革命
September 3, 2021 visual notes
RSA encryption colloquial explanation
Leetcode-12- integer to Roman numeral (medium)
Leetcode find duplicates
MySQL related summary
[latex] insérer une image
How to choose stocks? Which indicator strategy is reliable? Quantitative analysis and comparison of strategic benefits of ASI, VR, arbr, DPO and trix indicators
Downloading wiki corpus and aligning with multilingual wikis
切线与切平面
Status of the thread
Wangdao machine test - Chapter 6 - maximum common divisor GCD and minimum common multiple LCM
Alexnet实现Caltech101数据集图像分类(pytorch实现)
707. design linked list
leetcode. 349. intersection of two arrays
The tle4253gs is a monolithic integrated low dropout tracking regulator in a small pg-dso-8 package.
Leetcode-78- subset (medium)