Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions api-server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ const app = new Koa()
const KoaRouter = require('koa-router')
const router = new KoaRouter()

// 后台解决跨域响应头配置
app.use(async (ctx, next) => {
// 请求源白名单
const allowedOrigins = ['http://127.0.0.1:3000']
const requestOrigin = ctx.headers.origin
if(allowedOrigins.includes(requestOrigin)) {
ctx.set('Access-Control-Allow-Origin', requestOrigin)
ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
ctx.set('Access-Control-Allow-Headers', 'Content-Type')
ctx.set('Access-Control-Allow-Credentials', 'true')
}
await next()
})

// api
router.post('/api/task', async (ctx, next) => {
ctx.status = 200
Expand Down
2 changes: 1 addition & 1 deletion frontend/demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ <h5>响应</h5>
<script type="text/javascript">
const reqBtn = document.getElementById('requestBtn')
reqBtn.addEventListener('click', _ => {
// 3000端口的web页面去请求4000端口的api服务会跨域
// 后端配置对应响应头即可
axios.post('http://127.0.0.1:4000/api/task').then(res => {
console.log(res.data)
const resBox = document.getElementById('resBox')
Expand Down