这是我的第一个nodeJS项目,我已经卡住了。在package.json中“type”=“module”。我一直得到一个错误“ERR_MODULE_NOT_FOUND”。我尝试了默认和命名导出,但是都不起作用。
productRoutes.js
import express from 'express';
const router = express.Router();
router.get('/', (req, res) => {
res.status(200).json({ msg: 'get products' });
});
export default router;
server.js
import 'dotenv/config';
import express from 'express';
import mongoose from 'mongoose';
import routes from './api/v1/routes/productRoutes';
// express app
const app = express();
// middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log(req.path, req.method);
next();
});
// routes
app.use('/api/products', routes);
// connect to db
mongoose
.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('connected to database');
// listen to port
app.listen(process.env.PORT, () => {
console.log('listening for requests on port', process.env.PORT);
});
})
.catch((err) => {
console.log(err);
});
1条答案
按热度按时间avwztpqn1#
如果你不提供js文件的扩展名
.js
,节点编译器就无法理解它,除非你使用其他的传输器,比如babel。因此将
import routes from './api/v1/routes/productRoutes';
更改为import routes from './api/v1/routes/productRoutes.js';