【问题标题】:how to use 'require' on client side?如何在客户端使用“要求”?
【发布时间】:2021-08-14 09:33:42
【问题描述】:

我正在尝试使用 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);
}

这是获取温度信息并在浏览器中显示的服务器端代码

【问题讨论】:

  • 这对您有帮助吗? stackoverflow.com/questions/5168451/…
  • 我已经尝试过使用browseify,只是尝试添加“require.js”,但这并没有解决问题....我不知道我做错了什么
  • 您不能在浏览器中运行服务器或任何使用 nodejs require() 的代码。我建议您显示在浏览器中生成错误的实际代码,并解释您在浏览器中尝试使用该代码做什么。
  • Express 只能在后端运行,不能在浏览器中运行!

标签: node.js node-modules require


【解决方案1】:

这是因为浏览器/客户端中不存在require()。 在浏览器中使用<script>...</script> 标签。

【讨论】:

  • 在浏览器中使用是什么意思?
  • 您需要一个在客户端托管脚本的 html 页面吗?把脚本标签放在那里。
【解决方案2】:

尝试使用 browserify,如果您正在处理一个想要立即在客户端工作的小项目,它也是一个不错的快速扩展。 查看this 文章可能对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多