npm init
npm install
npm install express --save
express 文件名
app.js文件中修改:
第一种方式:
const express = require('express')const app = express()var path = require('path')var fs = require('fs')var iconv = require('iconv-lite');//设置跨域访问app.all('*', function(req, res, next) {res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "X-Requested-With");res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");res.header("X-Powered-By",' 3.2.1');res.header("Content-Type", "application/json;charset=utf-8");next();});// var questions = path.join(__dirname, './test.json')// var questions = [// {//name:'张三',//age:12// },// {//name:'李四',//age:15// },// {//name:'柠檬',//age:13// }// ]app.get('/123',function(req,res){res.status(200);// res.json(questions);//引入外部json文件fs.readFile('./test.json', {encoding:'binary'}, function(err, data) {if (err) {res.send('文件读取失败');} else {// res.send(data);var buf = Buffer.from(data,'binary');var str = iconv.decode(buf, 'GBK');res.send(str);}});})app.get('/', (req, res) => res.send('Hello World!'))app.listen(3000, () => console.log('app listening on port 3000!'))
第二种方式:
const express = require('express')const app = express()var path = require('path')var fs = require('fs')var iconv = require('iconv-lite');//设置跨域访问app.all('*', function(req, res, next) {res.header("Access-Control-Allow-Origin", "*");res.header("Access-Control-Allow-Headers", "X-Requested-With");res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");res.header("X-Powered-By",' 3.2.1');res.header("Content-Type", "application/json;charset=utf-8");next();});// var questions = path.join(__dirname, './test.json')// var questions = [// {//name:'张三',//age:12// },// {//name:'李四',//age:15// },// {//name:'柠檬',//age:13// }// ]app.get('/123',function(req,res){res.status(200);// res.json(questions);//引入外部json文件fs.readFile('./test.json', 'utf-8', function(err, data) {if (err) {res.send('文件读取失败');} else {res.send(data);}});})app.get('/', (req, res) => res.send('Hello World!'))app.listen(3000, () => console.log('app listening on port 3000!'))
如果觉得《nodejs读取本地json文件中文乱码问题》对你有帮助,请点赞、收藏,并留下你的观点哦!