简体   繁体   English

如何在客户端使用“要求”?

[英]how to use 'require' on client side?

I'm trying to set up a local server using node.js and the server works fine on the terminal but i got this error on the browser "Uncaught ReferenceError: require is not defined" any help will be appreciated thanks in advance我正在尝试使用 node.js 设置本地服务器,并且服务器在终端上工作正常,但我在浏览器上收到此错误“未捕获的 ReferenceError:未定义”任何帮助将不胜感激提前感谢

 // Setup empty JS object to act as endpoint for all routes projectData = {}; // Require Express to run server and routes const express=require('express'); //Require cors and body parser const cors=require('cors'); const bodyParser=require('body-parser'); // Start up an instance of app const app=express(); //Setting port to listen to const port=3200; //server testing server=app.listen(port,function(){ console.log(`server running on port ${port}`) }) /* Middleware*/ //Here we are configuring express to use body-parser as middle-ware. app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Cors for cross origin allowance app.use(cors()); // Initialize the main project folder app.use(express.static('website')); // Setup Server //setting up a get route app.get('/getRoute',getCallback()) //get function function getCallback(req,res){ res.send(projectData); console.log(projectData); } //setting up a post route app.post('/postRoute',postCallback()) //get function function postCallback(request,response){ newData={ temperature:request.body.temperature, date:request.body.date, userResponse:request.body.userResponse } projectData.push(newData); }

that's the server side code for getting temperature information and showing it in the browser这是用于获取温度信息并在浏览器中显示的服务器端代码

This is because require() does not exist in the browser/client-side.这是因为浏览器/客户端中不存在require() Use <script>...</script> tag in browser.在浏览器中使用<script>...</script>标签。

Try using browserify, and also it is a nice quick extension to use if you are working on a small project that you want to get working on the client-side right away.尝试使用 browserify,如果您正在处理一个想要立即在客户端工作的小项目,它也是一个不错的快速扩展。 check out this article it might help you.看看这篇文章它可能会对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM