express框架-基础篇

241 阅读2分钟

express中文官网

一、安装

npm install express --save

二、使用

1. 路由

文件目录

server.js
// server.js
const express = require('express') // 引入 express
const app = express()
//配置路由   匹配 URl 地址实现不同的功能
app.get('/', function(req, res) { // request 客户端请求, response 响应的数据, 告诉客户端回应什么数据
  res.send([
    {
      name: 'zhang',
      age: 18,
    }
  ])
})
app.get('/about', function(req, res) { // request 客户端请求, response 响应的数据, 告诉客户端回应什么数据
  res.send({message: 'about me'})
})

app.listen(3000, () => { // 监听3000端口
  console.log('3000!');
})
运行命令
node server.js

代码每次更新, 都需要执行一次 node server.js; 大家可以安装一下 nodemon , 使用 nodemon server.js 来运行, 这样每次保存代码的时候就可以实时监听代码的变化

打开浏览器输入: localhost:3000

输入 localhost:3000/about

2. 静态文件托管

文件目录

如何在浏览器看到 public 文件下的内容 -> express.static express内置 中间件函数
// server.js
app.use(express.static('public')) // 此时public下的静态文件都可以在浏览器访问到
浏览器中展示

express.static 函数提供服务的文件创建虚拟路径前缀
// server.js
app.use('static',express.static('public'))
浏览器中访问的路径

http://localhost:3000/static/index.html

http://localhost:3000/static/test.html

3. CORS跨域请求

// server.js
const express = require('express') // 变量express就是一个实例
const app = express()
app.use('/static',express.static('public'))
app.get('/data', function(req, res) {
  res.send([
    {
      id: 1,
      title: 'title-1',
    },
    {
      id: 2,
      title: 'title-2',
    },
    {
      id: 3,
      title: 'title-3',
    },
  ])
})

app.listen(3000, () => {
  console.log('3000!');
})
// public/index.html
 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>静态文件托管</title>
 </head>
 <body>
  <h3>index</h3>
  <script>
    fetch('http://localhost:3000/data')
    .then(res => res.json())
    .then(data => console.log(data))
  </script>
 </body>
 </html>

上述在静态文件 index.html 中, 请求了接口 http://localhost:3000/data 这个数据, 可以看下控制台输出, 拿到了数据

通过 live server 插件, 直接启动另外的一个服务器来打开静态文件 index.html

看下报错信息, 出现了跨域的问题, 那么如何来解决?

  • 安装跨域的包
npm i cors
  • server.js 中使用
app.use(require('cors')())

此时在 5500 这个端口就能正常请求到数据了