React proxy localhost not working, why?? MacOS Catalina

Viewed 897

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.

1 Answers

if you are going to use

proxy": "http://localhost:8000/"

as your proxy then at Node your route should not start with / because that would become http://localhost:8000//api/articles/:name/upvote (notice the extra /)

so it should be

app.post('api/articles/:name/upvote', async (req, res) => {

and to change the default PORT number try adding a port to the start script in package.json file

"scripts": {
   "start": "PORT=3000 react-scripts start",
 }
Related