简体   繁体   English

如何使用 NODEJS MONGODB 修复“无法获取”

[英]HOW DO I FIX "CANNOT GET" USING NODEJS MONGODB

I m testing a simple Get api with postman, but i am getting "cannot GET".我正在用邮递员测试一个简单的 Get api,但我得到“无法获取”。

server.js (in the root folder) server.js(在根文件夹中)

```const express = require('express');
const mongoose = require('mongoose');


const items = require('./routes/api/items');




const app = express();

//body Parser middleware

app.use(express.json());

//Db config

const db = require('./config/keys').mongoURI;

//const db = "mongodb+srv://gkmm:123123123@cluster0-bo4ln.mongodb.net/test?retryWrites=true&w=majority"

//Connect to mongo

mongoose
    .connect(db, { useNewUrlParser:true, useUnifiedTopology: true})
    .then(() => console.log('MongoDB Connected...'))
    .catch(err => console.log(err));

    const port = process.env.PORT || 4000;

    app.listen(port, () => console.log(`Server started on port ${port}`));


//Use routes

app.use('./routes/api/items.js', items);```

routes(root folder)/api/items.js路线(根文件夹)/api/items.js

```const express = require('express')
const router = express.Router();

//Item Model

const Item = require('../../models/Item')

//@route GET api/items
//@des Get AAll Items
//access public

router.get('/', (req, res) => {
    Item.find()
        .sort({ date: -1})
        .then(items => res.json(items));
});

module.exports = router; ```

Running into this error while trying to test my API, i checked my paths are correct, my database is connected.在尝试测试我的 API 时遇到此错误,我检查了我的路径是否正确,我的数据库已连接。 but i have no idea why is it returning 404 not found.但我不知道为什么它返回 404 not found。

After looking through your code, @ the line which you ask app to use your routes查看您的代码后,@您要求应用程序使用您的路线的行

//Use routes
/* You are telling the route to go through e.g. <yoururl>/./routes/api/items.js/
   in order to reach your GET in items.js
*/
app.use('./routes/api/items.js', items);```

To resolve this issue you can edit your app.use to要解决此问题,您可以将 app.use 编辑为

app.use('/test', items) // test is just an example, you can change it to other keywords

Then to access your items GET route use "/test/"然后访问您的项目 GET 路线使用“/test/”

Shouldn't app.use('./routes/api/items.js', items);不应该app.use('./routes/api/items.js', items); be app.use('/api/items', items);app.use('/api/items', items); ? ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM