0

感谢大佬点进来!


关于开发环境:

  • koa2 + vue
遇到的问题:

先看下目录结构吧,

clipboard.png

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目录及代码

clipboard.png

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页面
clipboard.png
点击search按钮时希望拿到后台数据
但是得到的结果却是

控制台

clipboard.png

network

clipboard.png

clipboard.png

▲ 以上便是我遇到的问题, 希望大佬帮帮忙!!

2019-06-11 提问
3 个回答
1

已采纳

不要使用*,配置成具体的域名,如下所示

 ctx.set("Access-Control-Allow-Origin", "http://localhost:8080")
0

顶顶顶,出来吧,大佬

0

前端设置转发后,就不会有跨域问题了,koa哪里,你不用设置cors了

撰写答案

推广链接