node.js - 如何通过执行节点 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);
它运行良好,但是当我尝试在本地主机上运行它时,它无法正常工作。
我写的程序是——
解决方案
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/
推荐阅读
- r - 在 RShiny 中处理表格后,根据用户先前的选择在 selectInput 中显示选项
- ibm-watson - 如何将 HTML 文件的特定部分导入 WDS?
- ionic-framework - 离子4慢编译时间
- css - 为什么 Vuetify CSS 在 Vue 实例之外应用?
- spring - Spring Data JPA 使用 SpEL 语法有条件地构建查询
- datagrip - 为什么 DataGrip 有时只显示查询执行时间?
- algorithm - 搜索实用大型机算法
- c# - 如何使用剃刀评估是否为空
- abap - 为什么 'FETCH NEXT CURSOR' 不选择数据?
- python - 如何为多处理池中的单个进程分配 python 请求会话?