生活随笔
收集整理的這篇文章主要介紹了
                                
vue ---  前端代理发送http请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
 
                                
                            
                            
                            后端
 
- 端口在3000
 - 使用jsonwebtoken和koa-jwt生成令牌并返回
 - 對’/api/userinfo’端口,先驗證令牌是否通過,若通過返回數據
 
 
const Koa 
= require('koa');
const Router 
= require('koa-router');
const jwt 
= require('jsonwebtoken');
const jwtAuth 
= require('koa-jwt');
const secret 
= 'odd marron';const app 
= new Koa();
const router 
= new Router();router
.get('/api/login', async ctx 
=> {const { username
, passwd 
} = ctx
.query
;console
.log(username
, passwd
);if (username 
=== 'admin' && passwd 
=== '123456') {const token 
= jwt
.sign({data
: { name
: '好吃的栗子' }, exp
: Math
.floor(Date
.now() / 1000) + 60 * 60 },secret
);ctx
.body 
= { code
: 1, token 
};} else {ctx
.status 
= 401;ctx
.body 
= { code
: 0, message
: '用戶名或密碼錯誤' };}
});router
.get('/api/userinfo',jwtAuth({ secret 
}),   async ctx 
=> {ctx
.body 
= {code
: 1,data
: {name
: '栗子',age
: 18}}}
)app
.use(router
.routes());
app
.listen(3000,()=>{console
.log('[server] server is runnint at http://127.0.0.1:3000');
});
 
前端
 
- 運行在8080端口,故產生了跨域
 - 在vue.config.js中添加代理
 - 對所有’/api’開頭的請求進行代理
 
 
configureWebpack
:{devServer
:{proxy
:{'/api':{target
: 'http://127.0.0.1:3000',changeOrigin
: true}}}
}
                            總結
                            
                                以上是生活随笔為你收集整理的vue ---  前端代理发送http请求的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                            
                                如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。