今天在网上学习的时候发现一个困惑我的问题
既然是静态的,可以考虑写在一个项目里面
vue.config.js配置代理
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
json文件中写入数据:
// message.json
{
"code":"000",
"message":"message",
"lists":[
{
"name":"小张",
"sex":"男",
"age": "21"
},
{
"name":"小丽",
"sex":"女",
"age":"18"
}
,
{
"name":"小白",
"sex":"女",
"age":"18"
}
]
}
前端进行数据请求:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>请求本地json文件数据</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function () {
// 请求路径是当前文件的相对路径
$.ajax({
url:'list.json',
contentType: 'application/json',
type: 'get',
dataType:'JSON',
success: function (res) {
console.log("成功");
if(res.code == '000'){
console.log(res);
$('body').html(JSON.stringify(res));
}else{
alert(res.message);
}
},
Error: function (xhr, type, errorThrown) {
console.log(errorThrown);
}
});
})
</script>
</body>
</html>
要在前端搭建一个允许跨域访问的接口,可以通过搭建一个临时的服务器,来提供访问数据的接口。
具体步骤如下:
// 安装express和cors依赖
npm install express cors
// 引入express和cors
const express = require('express');
const cors = require('cors');
// 创建express实例
const app = express();
// 允许所有域名跨域访问
app.use(cors());
// 设置监听端口
const PORT = 8000;
// 启动服务器
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
// 引入fs模块用于读取文件
const fs = require('fs');
// 创建路由处理请求
app.get('/api/data', (req, res) => {
// 读取json文件
fs.readFile('message.json', 'utf8', (err, data) => {
if (err) {
console.log(err);
res.status(500).json({ error: 'Internal Server Error' }});
} else {
// 将json字符串转换为json对象
const jsonData = JSON.parse(data);
// 返回json数据给前端
res.json(jsonData);
}
});
});
$(function () {
$.ajax({
url: 'http://localhost:8000/api/data',
contentType: 'application/json',
type: 'get',
dataType: 'json',
success: function (res) {
console.log("成功");
if (res.code == '000') {
console.log(res);
$('body').html(JSON.stringify(res));
} else {
alert(res.message);
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
node server.js
现在,你可以在浏览器中访问http://localhost:8080,前端就可以通过8080端口访问到8000端口上的数据了。