我正在尝试使用Node.js,Express和MongoDB构建REST API。到目前为止,一切似乎都可以进行。服务器启动并连接到数据库。 DB(命名为API)具有两个集合(文章和源)。我正在尝试将GET请求发送到Articles集合。但是,当我发送请求时,Postman会挂起,然后给出一个错误并导致服务器崩溃:
Could not get any response
There was an error connecting to localhost:3000/articles.
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General
服务器崩溃时会引发以下错误:
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
1: 0x10007e891 node::Abort() [/usr/local/Cellar/node/13.8.0/bin/node]
2: 0x10007e9c0 node::OnFatalError(char const*, char const*) [/usr/local/Cellar/node/13.8.0/bin/node]
3: 0x10017e6ab v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/usr/local/Cellar/node/13.8.0/bin/node]
我的代码如下:
require('dotenv').config()
const express = require('express')
const app = express()
const mongoose = require('mongoose')
mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true , useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('Connected to Database'))
app.use(express.json())
const articlesRouter = require('./routes/articles')
app.use('/articles', articlesRouter)
app.listen(3000, () => console.log('Server Started'))
我的路线;我正在尝试发送GET请求以获取数据库中所有文章(位于Articles集合中):
const express = require('express')
const router = express.Router()
const Article = require('../models/articles')
//Getting All Articles
router.get('/', async (req, res) => {
try {
const articles = await Article.find()
res.json(articles)
} catch (err){
res.status(500).json({message: err.message})
}
})
//Getting One Article
router.get('/:id', (req, res) => {
})
module.exports = router
如果我将router.get
更改为此router.get('/articles', async (req, res)
,邮递员将不再挂起,而是抛出以下错误:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /articles</pre>
</body>
</html>
我的路线:
const mongoose = require('mongoose')
const articlesSchema = new mongoose.Schema({
author: String, content: String, description: String, publishedAt: Date, source_id: String, summarization: String, title: String, url: String, urlToImage: String}, { collection: 'Articles'});
module.exports = mongoose.model('article', articlesSchema)
正如我在一开始提到的那样,这是我首次尝试构建REST API。您能提供的任何帮助来帮助我弄清为什么邮递员GET请求没有通过的帮助将不胜感激。
答案 0 :(得分:1)
您的代码似乎正确。 我遇到的一件事是在您指定的路线中
`router.get('/', async (req, res) =>{})`
,您将api称为
“ localhost:3000/articles
”不正确。
您尚未将任何路线指定为
router.get('/articles', async (req, res) =>{})
。
因此邮递员无法找到这样的路线,并且没有回应。
尝试使用我在上面指定的路由,或仅在路由中指定的地方调用“ localhost:3000/
”。
您可以做的其他事情就是将以下行放在 app.js 文件中,而无需更改代码中的其他任何内容。
app.use('/articles', articlesRouter)
希望这对您有所帮助。