![](/img/trans.png)
[英]Is it possible to run JavaScript on node.js on the browser(not cmd)
[英]Node.js runs in cmd but not in browser
我运行了这段代码,这是在jquery pro 2.0书中:
var http = require("http");
var querystring = require("querystring");
var port = 80;
http.createServer(function (req, res) {
console.log("[200 OK] " + req.method + " to " + req.url);
if (req.method == "POST") {
var dataObj = new Object();
var cType = req.headers["content-type"];
var fullBody = "";
if (cType && cType.indexOf("application/x-www-form-urlencoded") > -1) {
req.on("data", function(chunk) { fullBody += chunk.toString();});
req.on("end", function() {
res.writeHead(200, "OK", {"Content-Type": "text/html"});
res.write("<html><head><title>Post data</title></head><body>");
res.write("<style>th, td {text-align:left; padding:5px; color:black}\n");
res.write("th {background-color:grey; color:white; min-width:10em}\n");
res.write("td {background-color:lightgrey}\n");
res.write("caption {font-weight:bold}</style>");
res.write("<table border='1'><caption>Form Data</caption>");
res.write("<tr><th>Name</th><th>Value</th>");
var dBody = querystring.parse(fullBody);
for (var prop in dBody) {
res.write("<tr><td>" + prop + "</td><td>"
+ dBody[prop] + "</td></tr>");
}
res.write("</table></body></html>");
res.end();
});
}
}
}).listen(port);
console.log("Ready on port " + port);
使用命令行node.exe formserver.js这将返回'ready on port 90'。 无论何时我在我的浏览器上调用localhost:90,它都会在cmd中将请求注册为'200 OK GET to /'
在浏览器中它说“等待localhost”大约一分钟。 然后失败并显示“没有数据收到消息”。
在书中,作者正在使用www。 但是,我正在像大多数普通初学者一样使用'localhost'
我有两个问题,如何加载localhost以及在哪里保存我的html文件以便localhost可以看到它们。 它是否在保存上述代码的同一文件夹中? 或者在nodejs中的html文档中安装?
以下是一些可以获得一些结果的提示:
使用这些修改来获得至少一些结果:
var http = require("http"); var querystring = require("querystring"); var port = 8888; http.createServer(function (req, res) { console.log("[200 OK] " + req.method + " to " + req.url); if (req.method == "GET") { var dataObj = new Object(); var cType = req.headers["content-type"]; var fullBody = ""; res.writeHead(200, "OK", {"Content-Type": "text/html"}); res.write("<html><head><title>Post data</title></head><body>"); res.write("<style>th, td {text-align:left; padding:5px; color:black}\\n"); res.write("th {background-color:grey; color:white; min-width:10em}\\n"); res.write("td {background-color:lightgrey}\\n"); res.write("caption {font-weight:bold}</style>"); res.write("<table border='1'><caption>Form Data</caption>"); res.write("<tr><th>Name</th><th>Value</th>"); var dBody = querystring.parse(fullBody); for (var prop in dBody) { res.write("<tr><td>" + prop + "</td><td>" + dBody[prop] + "</td></tr>"); } res.write("</table></body></html>"); res.end(); } }).listen(port); console.log("Ready on port " + port);
在浏览器地址字段中输入localhost:8888
希望这能让您知道下一步该做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.