I have a problem with merging front-end and back-end in React framework. I had opened 3 terminals with: 1. Client side, 2. Database side and 3rd is with started mongodb ( sudo mongod --dbpath /System/Volumes/Data/data/db instead of mongod because of Catalina update ). I can't change localhost:3000 to localhost:8000 don't know why. Any suggestions?
Here are the codes from client and server:
Client:
const name = match.params.name;
const article = articleContent.find(article => article.name === name);
const [articleInfo, setArticleInfo] = useState({ upvotes: 0, comments: [] });
useEffect(() => {
const fetchData = async () => {
const result = await fetch(`/api/article/${name}`);
const body = await result.json();
console.log(body);
setArticleInfo(body);
}
fetchData();
}, [name]);
package.json:
"proxy": "http://localhost:8000/",
Server:
app.post('/api/articles/:name/upvote', async (req, res) => {
withDB(async (db) => {
const articleName = req.params.name;
const articleInfo = await db.collection('articles').findOne({ name: articleName });
await db.collection('articles').updateOne({ name: articleName }, {
'$set': {
upvotes: articleInfo.upvotes + 1,
},
});
const updatedArticleInfo = await db.collection('articles').findOne({ name: articleName });
res.status(200).json(updatedArticleInfo);
}, res);
});
app.post('/api/articles/:name/add-comment', (req, res) => {
const { username, text } = req.body;
const articleName = req.params.name;
withDB(async (db) => {
const articleInfo = await db.collection('articles').findOne({ name: articleName });
await db.collection('articles').updateOne({ name: articleName }, {
'$set': {
comments: articleInfo.comments.concat({ username, text }),
},
});
const updatedArticleInfo = await db.collection('articles').findOne({ name: articleName });
res.status(200).json(updatedArticleInfo);
}, res);
});
app.listen(8000, () => console.log('Listening on port 8000'));
Client starts on basic command: npm start, Server start with command: npx nodemon --exec npx babel-node src/server.js
Using program Postman, server work correct getting upvotes +1 each time on app.post function, also adding comments etc.