问题:
使用Express的过程中,使用import导入文件出现如下错误:
index.js:
import express from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import mongoose from 'mongoose'
import postRoutes from './routes/posts'
const app = express()
// 给路由添加了访问前缀
app.use('/posts', postRoutes)
app.use(bodyParser.json({ limit: '30mb', extended: true}))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true}))
app.use(cors())
const CONNECTION_URL = 'mongodb+srv://genhualu:xxxxxx@cluster0.yrjg9md.mongodb.net/?retryWrites=true&w=majority' //为了安全起见,此处密码被我处理掉了
const PORT = process.env.PORT || 5000
mongoose.connect(CONNECTION_URL).then(() => app.listen(PORT, () => console.log(`Server running on port ${PORT}`)))
.catch((error) => console.log('error: ', error.message))
// mongoose.set('useFindAndModify', false)
mongoose.set('strictQuery', true)
// https://cloud.mongodb.com/v2/6331478119994d3051fb1bd6#/clusters/connect?clusterId=Cluster0
posts.js:
import express from 'express'
const router = express.Router()
//localhost:5000/posts
router.get('/', (req, res) => {
res.send('THIS WORKS!')
})
export default router
目录结构如下:
解决方法:
将index.js文件的第6行代码
import postRoutes from './routes/posts'
改为
import postRoutes from './routes/posts.js'
总结:
在Express中,导入文件时不能省略后缀。