美文网首页
使用express框架的示例搭建node服务器

使用express框架的示例搭建node服务器

作者: 小棋子js | 来源:发表于2021-12-30 11:43 被阅读0次

最终目录结构

demo
│   node_modules
└───public
│   │   index.html
│   │   index.css
│   └───index.js
└───server.js

一、使用express框架的示例
1.下载express依赖

cnpm install express

2.server.js代码

//server.js
var express = require('express');
var app = express();
 
app.use(express.static('public'));//express.static是express提供的内置的中间件用来设置静态文件路径
 
app.get('/index.htm', function (req, res) {
    res.sendFile(__dirname + "/" + "index.htm");
})
 
var server = app.listen(3000, function () {
    console.log("监听3000端口")
})

3.public目录里面的index.html、index.css、index.js (其他几个方法公用这个文件夹的面问资源文件)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>本地服务器</title>
        <meta charset="UTF-8" />
        <link rel="stylesheet" type="text/css" href="index.css"/>
        <script src="index.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <h3>本地服务器</h3>
    </body>
</html>
//index.css
body{
    background: #fff000;
}
//index.js
console.log("index.html加载了index.js")

4.运行

node server.js

相关文章

网友评论

      本文标题:使用express框架的示例搭建node服务器

      本文链接:https://www.haomeiwen.com/subject/pkeiqrtx.html