我希望用户在本地主机3000上输入的数字显示在localhost 8000上。现在我已经创建了两个不同的应用程序/端口。但是,我得到一个"无法得到"在8000端口。 例如 - 如果用户转到端口3000,并在文本框中输入5。然后另一个用户应该能够转到8000,并看到输入了5。
节点js
var http = require('http');
var express= require('express')
var fs = require('fs');
var util = require('util');
var app= express();
var app2=express();
var multer = require('multer');
var dgram= require('dgram');
var client= dgram.createSocket('udp4');
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', function(req, res){
var html = fs.readFileSync('index2.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
app.post('/', function(req,res) {
res.send(req.body.number);
});
app2.get('/', function(req, res){
res.send();
});
app2.post('/', function(req, res){
res.send(req.body.number);
});
//Listening to computer's IP address
app.listen(3000, "192.168.0.172");
app2.listen(8000, "192.168.0.172");
console.log('Listening at 192.168.0.172:3000')
HTML
<html>
<head>
<title>
File Upload Example
</title>
</head>
<body>
<h1>Reading in Value</h1>
<form action="192.168.0.172:8000" method="post" enctype='multipart/form-data'>
<br/>
<label>Enter a Number</label>
<br/><br/>
<input type="text" name="number">
<br/><br/>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
答案 0 :(得分:0)
&#34;不能GET&#34;抛出错误是因为您已在app2:8000上声明了POST路由,而不是GET。
app2.get('/', function(req, res){
res.status(200).json({ping: 'pong'});
});
为了将html表单中的输入数字显示到app2:8000,您需要使用bodyparser中间件,如下所示:
const bodyParser = require('body-parser');
app2.use(bodyParser.json());
app2.use(bodyParser.urlencoded({
extended: true
}));
app2.post('/', function(req, res) {
res.send(req.body.number);
});
app2.listen(8000, '192.168.0.172');