Nodejs学习笔记——express实现静态服务器

结构:
在这里插入图片描述
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/style.css">
</head>
<body>
    <h1 class="bg">Nodejs</h1>
    <img src="./img/W.jpg" alt="">

    <script>
        fetch('/api/userList').then((res)=>{
    
    
            return res.json();
        }).then((res)=>{
    
    
            console.log(res);
            res.userList.forEach((item,index)=>{
    
    
                let newDiv = document.createElement('div');
                newDiv.innerHTML = '姓名:'+item.username+',性别:'+item.sex;
                document.body.appendChild(newDiv);
            })
        })
    </script>
</body>
</html>

style.css

.bg{
    
    
    background-color: skyblue;
}

img{
    
    
    width: 1000px;
}

app.js

//express框架
const express = require('express');

//实例化服务器应用
let app = express();

//实现静态服务器
app.use(express.static('static'))

//实现自定义接口
app.get('/api/userList',(req,res)=>{
    
    
    //请求的信息:req对象
    //响应的操作和信息:res对象
    res.json({
    
    
        state:'OK',
        userList:[
            {
    
    username:'vue',sex:'男'},
            {
    
    username:'js',sex:'男'},
            {
    
    username:'jq',sex:'男'}
        ]
    })
})

//启动服务器
app.listen(3000,function(){
    
    
    console.log('服务器启动:','http://127.0.0.1:3000');
})

配置环境:

在这里插入图片描述
在这里插入图片描述
启动服务后的界面:
在这里插入图片描述
fetch接受到的数据
在这里插入图片描述
渲染在页面上
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Nozomi0609/article/details/109511445