express.js 开发常见问题

express.js 开发常见问题

无法访问css、js等

添加静态资源文件夹

1
2
3
4
5
6
7
8
9
10
11
12
const express = require('express')
const bodyParser = require('body-parser')
const path = require('path');
const app = express()

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));
app.use(express.static('./public'));
app.use(express.static('./'));
app.use(express.static('.'));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

允许跨域

1
2
3
4
5
6
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
next()
})

本机IP地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const os = require('os');

/**
* 获取当前机器的ip地址
*/
function getIpAddress() {
var ifaces = os.networkInterfaces()
for (var dev in ifaces) {
let iface = ifaces[dev]
for (let i = 0; i < iface.length; i++) {
let { family, address, internal } = iface[i]
if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
return address
}
}
}
}

二维码命令行打印

1
2
3
const qrcode = require('qrcode-terminal')

qrcode.generate(`http://${ip}:${PORT}`, { small: true })

局域网无法访问

关闭系统防火墙,设置windows「专有网络」


express.js 开发常见问题
https://taylorandtony.github.io/2025/01/24/js-express-problems/
作者
TaylorAndTony
发布于
2025年1月24日
许可协议