文章目录
- ⭐前言
- ⭐初始化项目
- 调整npm 的script运行入口
- 搭建hello world的http服务
- npm run dev执行主函数的http服务
- ⭐http返回类型
- html模板文件返回
- 安装express
- 渲染html的字符串
- 渲染html文件 sendFile
- 渲染json返回数据类型 res.json
- ⭐结束
⭐前言
大家好,我是yma16,本期分享node搭建http服务的教程。
往期文章
node_windows环境变量配置
node_npm发布包
linux_配置node
node_nvm安装配置
⭐初始化项目
创建一个node_server目录
$ mkdir node_server
$ cd node_server
npm init
初始化package.json文件
$ npm init
安装 http依赖
$ npm install http
调整npm 的script运行入口
调整script的dev 为node 执行的入口 main/index.js文件
{
"name": "node_server",
"version": "1.0.0",
"description": "http server ",
"main": "main/index.js",
"scripts": {
"dev": "node ./main/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "yma16",
"license": "ISC",
"dependencies": {
"http": "^0.0.1-security"
}
}
搭建hello world的http服务
index.js写一个http返回
const { createServer } = require('http');
const honstname= '127.0.0.1';
const port= '3000';
const server = createServer((req, resp) => {
// the first param is status code it returns
// and the second param is response header info
resp.statusCode=200;
resp.setHeader({ 'Content-Type': 'text/plain' })
// resp.writeHead(200, { 'Content-Type': 'text/plain' });
console.log('server is working...');
// call end method to tell server that the request has been fulfilled
resp.end('Hello World');
});
server.listen(port, honstname, (error) => {
if (error) {
console.log('Something wrong: ', error);
return;
}
console.log(`Server running at http://${hostname}:${port}/`);
});
npm run dev执行主函数的http服务
执行npm run dev
$ npm run dev
浏览运行的http地址 http://localhost:3000,出现搭建的hello world 说明搭建的http服务成功
⭐http返回类型
指定http返回的类型
- html文件
- json数据类型
html模板文件返回
渲染一个类似于python的web框架django渲染template
安装express
$ npm install express
渲染html的字符串
使用express渲染html的字符串
const hostname = '127.0.0.1';
const port = 3000;
const express = require("express");
const app = express();
app.listen(port,hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
app.get("/", (req, res) => {
res.send("<html> <head>server Response</head><body><h1> This page was render direcly from the server <p>Hello there welcome to my website</p></h1></body></html>");
});
访问页面渲染html成功
渲染html文件 sendFile
login的html文件 一个登录的效果
在inscode查看效果
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>login</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
body {
background: #5D4157;
/* fallback for old browsers */
background: -webkit-linear-gradient(to left, #A8CABA, #5D4157);
/* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to left, #A8CABA, #5D4157);
/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
animation: backdiv 12s infinite;
background-position: 0% 50%;
background-size: 400%;
}
@keyframes backdiv {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
.title {
text-align: center;
padding: 50px 0 20 px;
}
.title h1 {
margin: 0;
padding: 0;
color: #fff;
/* text-transform: uppercase; */
font-size: 36px;
}
.container {
width: 50%;
height: 400px;
margin: 0 auto;
border: 2 px solid #fff;
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.5);
}
.container .left {
float: left;
width: 50%;
height: 400px;
background: url(./html/img/background.jpg);
background-size: cover;
box-sizing: border-box;
}
.container .right {
float: right;
width: 50%;
height: 400px;
box-sizing: border-box;
background: #fff;
}
.formBox {
width: 100%;
padding: 80px 40px;
height: 400px;
background: #fff;
box-sizing: border-box;
/* opacity: 0.6; */
}
.formBox .p {
margin: 0;
padding: 0;
font-weight: bold;
color: #a6af13;
}
.formBox input {
width: 100%;
margin-bottom: 20px;
}
.formBox input[type="text"] {
border: none;
border-bottom: 2px solid #a6af13;
outline: none;
height: 40px;
}
.formBox input[type="password"] {
border: none;
border-bottom: 2px solid #a6af13;
outline: none;
height: 40px;
}
.formBox input[type="text"]:focus {
border-bottom: 2px solid #262626;
}
.formBox input[type="password"]:focus {
border-bottom: 2px solid #262626;
}
.formBox input[type="submit"] {
border: none;
outline: none;
height: 40px;
color: #fff;
background: #262626;
cursor: pointer;
}
.formBox input[type="submit"]:hover {
background: #a6af13;
}
.formBox a {
font-weight: bold;
color: #262626;
font-size: 12px;
}
</style>
<body>
<div class="title">
<h1>login form</h1>
</div>
<div class="container">
<div class="left"></div>
<div class="right">
<div class="formBox">
<form>
<p>username</p>
<input type="text" name="" placeholder="name" />
<p>password</p>
<input type="password" name="" placeholder="password" />
<input type="submit" name="" value="sign" />
<a href="#">forget password</a>
</form>
</div>
</div>
</div>
</body>
</html>
index内容
const hostname = '127.0.0.1';
const port = 3000;
const express = require("express");
const app = express();
app.listen(port,hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// server your css as static
app.use(express.static(__dirname));
app.get("/", (req, res) => {
console.log(__dirname)
res.sendFile(__dirname + "/html/login.html");
});
访问出现html的内容
渲染json返回数据类型 res.json
const hostname = '127.0.0.1';
const port = 3000;
const express = require("express");
const app = express();
app.listen(port,hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// server your css as static
app.use(express.static(__dirname));
app.get("/", (req, res) => {
console.log(__dirname)
res.json({
code:200,
data:'hello yma16',
msg:'csdn'
})
});
预览,返回json成功!
⭐结束
感谢你的阅读,如有不足欢迎指出!