NodeJS项目前端weather.js运行时报ReferenceError: require is not defined求助
问题根源
你报错的weather.js存放在public静态资源目录下,是被EJS模板引入后运行在用户浏览器端的代码,和运行在服务端NodeJS进程里的app.js属于完全不同的运行环境:
- 浏览器端JS没有内置的CommonJS模块系统,所以不存在
require方法 - 浏览器端出于安全限制,完全不允许直接操作本地文件系统,就算你解决了require的问题,
fs模块也不可能在浏览器里运行
你之前安装的requirejs、browserify都解决不了这个问题:requirejs是浏览器端的AMD模块加载工具,不支持加载NodeJS原生模块;browserify虽然可以把CommonJS规范的代码打包到浏览器运行,但fs这类依赖操作系统底层能力的原生模块,是根本无法被打包到浏览器侧使用的。
解决方案
根据你的实际需求选对应方案即可:
方案1:需要把生成的JSON文件存储到服务端
把写文件的逻辑移到服务端实现即可:
- 首先修改
app.js,新增一个接收天气数据的POST接口:
const express = require('express') const fs = require('fs') const path = require('path') const app = express() const port = 3000 // 原有静态资源、模板配置保持不变 app.use(express.static('public')) app.use('./css', express.static(__dirname + 'public/css')) app.use('./js', express.static(__dirname + 'public/js')) app.use('./img', express.static(__dirname + 'public/img')) app.set('views', './views') app.set('view engine', 'ejs') // 新增解析JSON请求体的配置 app.use(express.json()) // 新增保存天气数据的接口 app.post('/save-weather', (req, res) => { const data = req.body const _myObject = JSON.stringify(data); const filePath = path.join(__dirname, 'public/js/data2.json') fs.writeFile(filePath, _myObject, 'utf8', (err) => { if (err) { return res.status(500).json({success: false, msg: '写入失败'}) } res.json({success: true, msg: '写入成功'}) }) }) app.get('', (req, res) => { res.render('index') }) app.listen(port, () => console.info(`Listening on port ${port}`))
- 然后修改
weather.js,删掉fs相关的代码,改成调用服务端接口:
const api_key = config.API_KEY_WEATHER async function calcWeather(){ const info = await fetch('../js/data.json') .then(function(response) { return response.json(); }); for (var i in info) { const lat = info[i][0].latjson; const long = info[i][0].lonjson; const base = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${api_key}&units=metric&lang=sp`; fetch(base) .then((responses) => { return responses.json(); }) .then((data) => { var myObject = { Latitud: data.coord.lat, Longitud: data.coord.lon, Temperatura: data.main.temp, Ciudad: data.name, Humedad: data.main.humidity, Descripcion: data.weather[0].description, }; // 改为调用服务端接口存文件 fetch('/save-weather', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(myObject) }).then(res => res.json()).then(res => { if (res.success) { console.log('File is written successfully!') } else { console.log(`Error writing file: ${res.msg}`) } }) }); } };
方案2:需要把生成的JSON下载到用户本地
不需要调用服务端接口,直接用浏览器自带的下载能力即可,把weather.js里fs相关的代码替换为以下内容:
const _myObject = JSON.stringify(myObject); const blob = new Blob([_myObject], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'data2.json'; a.click(); URL.revokeObjectURL(url); console.log('文件已触发下载')
内容的提问来源于stack exchange,提问作者Martín JF
相关产品推荐
相关产品推荐

