vuex+koa 前端取不到数据

http://localhost:3000/getRencentJob  这个是一个json数据的接口
// 注意require('koa-router')返回的是函数:
const router = require('koa-router')()
const fs=require('fs')
const cors=require('koa-cors')

router.get('/getRencentJob',async (ctx, next)=>{
    await cors();
    ctx.body=JSON.parse(fs.readFileSync('./static/recentJob.json'))
    
})


module.exports=router

我前端8080 想跨域取数据

const actions = {
    getJson(context){
    // 调用我们的后端getJson接口
    fetch('http://127.0.0.1:3000/getRencentJob', {
      method: 'GET',
      mode:'cors',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    }).then(function (res) {
        console.log(res)
      if(res.status === 200){
          
          
        return res.json()
      }
    }).then(function (json) {

     // console.log(typeof Array.from(json), Array.from(json));
      context.commit('setJson', json);
    })
  }
};

还是报错

recentJob.js?a162:18 OPTIONS http://localhost:3000/getRencentJob 404 (Not Found)
getJson @ recentJob.js?a162:18
wrappedActionHandler @ vuex.esm.js?358c:704
dispatch @ vuex.esm.js?358c:426
boundDispatch @ vuex.esm.js?358c:332
getJson @ dashboard.vue?07b0:81
mounted @ dashboard.vue?07b0:87
callHook @ vue.esm.js?efeb:2921
insert @ vue.esm.js?efeb:4158
invokeInsertHook @ vue.esm.js?efeb:5960
patch @ vue.esm.js?efeb:6179
Vue._update @ vue.esm.js?efeb:2660
updateComponent @ vue.esm.js?efeb:2788
get @ vue.esm.js?efeb:3142
Watcher @ vue.esm.js?efeb:3131
mountComponent @ vue.esm.js?efeb:2795
Vue.$mount @ vue.esm.js?efeb:8540
Vue.$mount @ vue.esm.js?efeb:10939
Vue._init @ vue.esm.js?efeb:4640
Vue @ vue.esm.js?efeb:4729
(anonymous) @ main.js?1c90:16
./src/main.js @ app.js:3856
webpack_require @ app.js:679
fn @ app.js:89
0 @ app.js:3897
webpack_require @ app.js:679
(anonymous) @ app.js:725
(anonymous) @ app.js:728
:8080/#/:1 Failed to load http://localhost:3000/getRencentJob: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
vue.esm.js?efeb:8555 Download the Vue Devtools extension for a better development experience:
https://github.com/vuejs/vue-...
:8080/#/:1 Uncaught (in promise) TypeError: Failed to fetch

该怎么写呀 新手上路

阅读 3.4k
4 个回答

const cors=require('koa2-cors')

app.use(cors({

origin: function (ctx) {
   
        return "*"; // 允许来自所有域名请求
   
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],

}))

跨域了 , 安装koa-cors,注意版本是koa1还是koa2的

另一个答案正解

需要为KOA配置一个koa-cors来允许跨域请求。

因为在跨域的时候,浏览器会去后端查询headers是否列出了支持跨域的方法和域。
所以需要在后端提供这个headers,最简单的就是koa-cors

vue config 中设置 proxy 也可以跨域,不过仅限开发的时候使用,打包后无效。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题