首页 > 解决方案 > 如何通过执行节点 js 文件生成 localhost URL?

问题描述

我在 Brackets Text Editor 上写了一个 node js 的程序,并将其保存为 name first.js。当我使用命令提示符执行它时 - node first.js

var http = require('http');

function onRequest(req,res)
{
    res.writeHead(200,{'Content-Type':'text/plain'});
    res.write('hello js');
    res.end();
}
http.createServer(onRequest).listen(8080);

它运行良好,但是当我尝试在本地主机上运行它时,它无法正常工作。

我写的程序是——

标签: node.js

解决方案


you can create a simple http server using express (be sure that u have the packaged installed , you can install express using npm : npm install express) .

your server.js code is :

const express = require("express");
const app = express();
const port = process.env.PORT || 4000;

app.get("/", (req, res) => {
console.log("response");
});
app.listen(port, () => {
  console.log("Server listining on port ", port);
});

lets say you save this file in c:/folder , open cmd in the same folder
run : node server.js .
now go to your browser and check : http://localhost:4000/

推荐阅读