koa2设置了koa2-cors为何还会跨域失败?
感谢大佬点进来!
关于开发环境:
- koa2 + vue
遇到的问题:
先看下目录结构吧,
koa2里面的app.js
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const index = require('./routes/index')
const users = require('./routes/users')
const goods = require('./routes/goods')
const cors = require('koa2-cors')
// error handler
onerror(app)
// middlewares
app.use(cors({
origin: function (ctx) {
console.log(ctx)
if (ctx.url === '/goods') {
return "*"; // 允许来自所有域名请求
}
return 'http://localhost:8080';
},
methods:['GET','POST'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
/**
* 另一种写法
* var cors = require('koa2-cors');
* app.use(cors())
*/
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
extension: 'pug'
}))
// logger
app.use(async (ctx, next) => {
ctx.set("Access-Control-Allow-Origin", "*")
// ctx.set("Access-Control-Allow-Headers", "X-Requested-With")
ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
ctx.set("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(goods.routes(), goods.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
module.exports = app
routers里面的goods.js
const router = require('koa-router')()
const mongoose = require('mongoose')
const goods = require('../models/goods')
router.prefix('/goods')
mongoose.connect('mongodb://127.0.0.1:27017/koa', { useNewUrlParser:true })
router.get('/', async (ctx, next) => {
let res = await goods.find()
ctx.response.body = res
console.log(res)
})
module.exports = router
models下的goods.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const productSchema = new Schema({
'name': String,
'price': Number
})
module.exports = mongoose.model('goods', productSchema)
▲以上大概就是koa2的所有代码了,非常感谢大佬阅读至此。
vue目录及代码
router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: () => import('./views/About.vue')
},
{
path: '/login',
name: 'login',
component: () => import('./views/login.vue')
}
]
})
axios代码
import axios from 'axios'
axios.defaults.withCredentials = true
let base = 'http://127.0.0.1:3000' // local Address
let config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
export const login = params => { return axios.post(`${ base }/login`, params, config).then(res => res.data) }
export const goods = params => { return axios.get(`${base}/goods`, { params: params }) }
html 代码
<template>
<div>
<button @click="handleSearch">search</button>
{{ list }}
</div>
</template>
<script>
import { goods } from '../api'
export default {
data () {
return {
list: []
}
},
methods: {
handleSearch () {
let para = {}
goods(para).then((res) => {
console.log(res)
})
}
}
}
</script>
<style lang="stylus" scoped>
</style>
vue.config.js
module.exports = {
baseUrl: '/', // 主要改这
outputDir: 'dist',
lintOnSave: true,
runtimeCompiler: true,
chainWebpack: () => {},
configureWebpack: () => {},
devServer: {
proxy: {
'/goods': {
target: 'http://127.0.0.1:3000',
changeOrigin: true
}
}
}
}
vue项目启动在8080端口,koa启动在3000端口,
当我在login页面
点击search按钮时希望拿到后台数据
但是得到的结果却是
控制台
network
▲ 以上便是我遇到的问题, 希望大佬帮帮忙!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要使用*,配置成具体的域名,如下所示
return "*"; 这句替换成 return ctx.header.origin; 即可实现所有跨域
顶顶顶,出来吧,大佬
前端设置转发后,就不会有跨域问题了,koa哪里,你不用设置cors了