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
该怎么写呀 新手上路
const cors=require('koa2-cors')
app.use(cors({
}))