Math.random() 在 nodejs 的浏览器中不起作用
Math.random() is not working in browser in nodejs
我正在 node 中编写此代码,但是 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.send([Body]) 不希望发送号码。
The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.
查看您的错误,似乎允许使用更早的数字并隐式用作 HTTP Status Codes
(例如:200,404,201)。现在,当使用 .send()
发送状态代码时,Express 认为您仍在使用版本中的旧语法是正常的。现在它已被弃用。无论如何,8 不是有效代码。
你可以这样做:
res.send({'random' : x });
你的错误还让你知道如果你想发送状态,你可以简单地使用 res.sendStatus(200) 等。不过你可能不希望这样。
问题不在于随机,而是您以错误的方式返回响应。
res.sendStatus(200).json(x)
我正在 node 中编写此代码,但是 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.send([Body]) 不希望发送号码。
The body parameter can be a Buffer object, a String, an object, Boolean, or an Array.
查看您的错误,似乎允许使用更早的数字并隐式用作 HTTP Status Codes
(例如:200,404,201)。现在,当使用 .send()
发送状态代码时,Express 认为您仍在使用版本中的旧语法是正常的。现在它已被弃用。无论如何,8 不是有效代码。
你可以这样做:
res.send({'random' : x });
你的错误还让你知道如果你想发送状态,你可以简单地使用 res.sendStatus(200) 等。不过你可能不希望这样。
问题不在于随机,而是您以错误的方式返回响应。
res.sendStatus(200).json(x)