【问题标题】:Math.random() is not working in browser in nodejsMath.random() 在 nodejs 的浏览器中不起作用
【发布时间】:2021-07-11 06:15:58
【问题描述】:

我正在节点中编写此代码,但是当我点击地址时,Math.random() 在浏览器中不起作用,它显示错误,但在 cmd 中它工作正常,即 comsole.log(x)。

错误是enter image description here

var express = require('express');
var app = express();

app.get("/",function(req,res){
    console.log("Someone Requested Us!");
    res.send("You've Reached The Home Page"); //res.write("Hello World");
    res.end();
});

app.get("/random_num",function(req,res){
    const x = Math.floor(Math.random() * 10) + 1 ;
    console.log(x);
    res.send(x);
    //res.end();
});

app.listen(3000, function(){
    console.log("Server Running On 3000");
});

【问题讨论】:

  • 错误信息似乎在告诉你该怎么做:) 使用res.sendStatus() 而不是res.send(x)。 ...发生这种情况是因为您发送了一个号码,所以 express 认为您发送的只是一个 http 状态代码。
  • 欢迎来到 SO。请将错误消息以文本形式而不是图像形式发布。

标签: javascript html node.js express backend


【解决方案1】:

res.send([Body]) 不希望发送号码。

body 参数可以是 Buffer 对象、String、对象、Boolean 或 Array。

查看您的错误,似乎更早的数字被允许并被隐式用作HTTP Status Codes(例如:200,404,201)。现在,express 认为您在使用 .send() 发送状态代码是正常的时仍在使用版本中的旧语法。现在它已被弃用。无论如何,8 不是有效代码。

你可以这样做:

res.send({'random' : x });

您的错误还让您知道,如果您想发送状态,您可以简单地使用 res.sendStatus(200) 等。不过你可能不希望这样。

【讨论】:

    【解决方案2】:

    问题不在于随机问题,而是您以错误的方式返回响应。

    res.sendStatus(200).json(x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 2015-05-06
      • 2020-04-27
      • 2012-10-23
      • 2017-10-13
      相关资源
      最近更新 更多