Я следую руководству по React, в котором я создаю базовый блог в стеке MERN.
В этом конкретном случае в моем Server.js
файле я пытаюсь POST
запрос к MongoDB. Он идентифицирует коллекцию и объект JSON с помощью параметров URL, изменяет объект и возвращает новую константу, равную новому объекту.
Проблема в том, что const
, равный найденному объекту, не определен. Однако я не могу понять, почему это так. Другая функция, использующая запрос GET
с тем же самым const
(каждая из которых является локальной для своих соответствующих функций), работает так, как задумано, без ошибок в определении const
.
import express from 'express';
import bodyParser from 'body-parser';
import { MongoClient } from 'mongodb';
const app = express();
// also tried to use express' built in bodyparser, same error
app.use(bodyParser.json());
// working GET req function using the same const
app.get('/api/articles/:name', async (req,res) => {
try {
const articleName = req.params.name;
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('my-app-db');
// this is the const in question, equal to object found
// based on name param passed in URL
const articleInfo = await db.collection('articles').findOne({ name: articleName });
res.status(200).json(articleInfo);
console.log(articleInfo);
client.close();
} catch (error) {
res.status(500).json({message: 'Error connecting to db', error});
}
});
// non working POST req function, using the same const
// added slash to front of path as it was originally missing, still
// getting error
app.post('/api/articles/:name/upvote', async (req,res) => {
try {
const articleName = req.params.name;
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('my-app-db');
// gets error for being undefined at Server.js 32:5
const articleInfo = await db.collection('articles').findOne({ name: articleName });
await db.collection('articles').updateOne({ name: articleName },{
'$set' : {
upvotes: articleInfo.upvotes + 1,
},
});
// this is updated article sent as response
const updatedArticleInfo = await db.collection('articles').findOne({ name: articleName });
res.status(200).json(updatedArticleInfo);
client.close();
} catch (error) {
res.status(500).json({message: 'Error connecting to db', error});
}
})
app.listen(8000, () => console.log('Listening on port 8000'));
Это ошибка, точно такая же, как и в Postman.
ReferenceError: articleInfo не определен
в C: \ Users \ oduboise \ Desktop \ sandbox \ react-full-stack \ my-app-backend \ src / Server.js: 32: 5
в Layer.handle [как handle_request] (C: \ Users \ oduboise \ Desktop \ sandbox \ response-full-stack \ my-app-backend \ node_modules \ express \ lib \ router \ layer.js: 95: 5)
в следующий (C: \ Users \ oduboise \ Desktop \ sandbox \ response-full-stack \ my-app-backend \ node_modules \ express \ lib \ router \ route.js: 137: 13)
в Route.dispatch (C: \ Users \ oduboise \ Desktop \ sandbox \ response-full-stack \ my-app-backend \ node_modules \ express \ lib \ router \ route.js: 112: 3)
в Layer.handle [как handle_request] (C: \ Users \ oduboise \ Desktop \ sandbox \ response-full-stack \ my-app-backend \ node_modules \ express \ lib \ router \ layer.js: 95: 5)
в C: \ Users \ oduboise \ Desktop \ sandbox \ response-full-stack \ my-app-backend \ node_modules \ express \ lib \ router \ index.js: 281: 22
в параметре (C: \ Users \ oduboise \ Desktop \ sandbox \ response-full-stack \ my-app-backend \ node_modules \ express \ lib \ router \ index.js: 354: 14)
в параметре (C: \ Users \ oduboise \ Desktop \ sandbox \ response-full-stack \ my-app-backend \ node_modules \ express \ lib \ router \ index.js: 365: 14)
в Function.process_params (C: \ Users \ oduboise \ Desktop \ sandbox \ response-full-stack \ my-app-backend \ node_modules \ express \ lib \ router \ index.js: 410: 3)
в следующий (C: \ Users \ oduboise \ Desktop \ sandbox \ response-full-stack \ my-app-backend \ node_modules \ express \ lib \ router \ index.js: 275: 10)
Это ответ на успешный запрос GET
в виде объекта JSON.
{
"_id": "5ec60f1390d2ce923cdb0e41",
"name": "what-react",
"upvotes": 0,
"comments": []
}
Я также впервые задаю вопрос в StackOverflow, обычно я могу это выяснить / найти. Так что любые советы по форматированию вопросов также будут оценены
articleName
внутри метода публикации. какую ценность вы получаете от этого - person Vivek Doshi   schedule 23.05.2020/api/articles/:name/upvote
. При этом, как уже было сказано, ответ по-прежнему показывает Server.js: 32: 5, независимо от того, какие изменения были внесены в Server.js ... - person okd_v   schedule 23.05.2020