我正在尝试发出 http 请求并在浏览器中打开特定页面。我已经尝试了几个软件包,例如 npm opn、npm open、openurl 但我无法达到预期的目标。这就是我正在尝试的:
服务器.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
response = {
fname:req.body.fname,
surname:req.body.surname,
age:req.body.age,
phone:req.body.phone,
city:req.body.phone,
email:req.body.email,
country:req.body.country,
postal_code:req.body.postal_code,
password:req.body.password
};
console.log(response);
res.end(JSON.stringify(response));
var exportJson= JSON.stringify(response);
fs.writeFile("input.txt", exportJson, function(err) {
if(err) {
return console.log(err);
}
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Listening at http://%s:%s", host, port)
})
客户端.js
var http = require('http');
var opn=require('opn');
// Options to be used by request
var options = {
host: '127.0.0.1',
port: '8081',
path: '/index.html'
};
//opn("https://google.pt");
var callback = function(response){
// Continuously update stream with data
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
console.log(body);
});
}
var req = http.request(options, callback);
req.end();
编辑:
我需要通过连接到服务器/本地主机的客户端文件打开浏览器(页面是一个表单)。使用像 opn 这样的 npms 打开只会打开文档,例如:
opn(__dirname + "/" + "index.html"); //this line in the client.js
我想要这样的东西:
var req = http.request(options, callback);
opn(options.path);//with this line, when running the client.js (with the server on), the program opens another command prompt...
req.end();
最佳答案
opn(options.path);
不起作用,因为您应该使用完整路径调用 opn
,即 opn('http://127.0.0.1 :8081/index.html')
关于javascript - 客户端http请求打开特定页面问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43934469/