nuxt跨域读取数据:
node.js写RESTful API
- 在node.js同一个文件下写一个list.json
{
"user1" : {
"name" : "mahesh",
"password" : "password1",
"profession" : "teacher",
"id": 1
},
"user2" : {
"name" : "suresh",
"password" : "password2",
"profession" : "librarian",
"id": 2
},
"user3" : {
"name" : "ramesh",
"password" : "password3",
"profession" : "clerk",
"id": 3
}
}
- 用node.js写RESTful API
var express = require('express');
var app = express();
var fs = require("fs");
var path = require('path'); //系统路径模块
//创建get接口
app.get('/list', function (req, res) {
fs.readFile( './list.json','utf8', function (err, data) {
console.log( data );
res.end( data );
});
})
var server = app.listen(3001, function () {
var port = server.address().port
console.log("应用实例,访问地址为 http://localhost:%s", port)
})
浏览器显示如图:
终端显示:
nuxt部分
首先导入axios模块,在模块中导入axios
在nuxt-config-js,
//跨域
axios: {
proxy: true
},
proxy: {
"/api": "http://localhost:3001"//代理转发的地址
},
在.vue文件里头
export default {
async asyncData({$axios}){
let res1 = await $axios({URL:'http://localhost:3001/list'});
//读取接口里头的数据
console.log("读取跨域数据",res1.data.user1);
}
}
f12检查:读取到跨域数据
读取数据显示在页面上
<template>
<div>
<h1>获取跨域数据</h1>
<!-- 读取跨域数据 -->
<h2>
{{this.id}}:{{this.name}}-{{this.age}}
</h2>
</div>
</template>
<script>
export default {
data(){
return{
id:'',
name: '',
age: ''
}
},
async asyncData({$axios}){
let res = await $axios({
url:'http://localhost:3001/list'});
console.log('读取的跨域资源',res.data.user1);
return{
id:res.data.user1.id,
name:res.data.user1.name,
age:res.data.user1.age
}
}
}
</script>
<style>
</style>