React proxy localhost不起作用,为什么? MacOS Catalina

问题描述 投票:2回答:1

我在React框架中合并前端和后端时遇到问题。我用以下方法打开了3个终端:1.客户端,2.数据库端,第三个是启动的mongodb(由于Catalina update,所以sudo mongod --dbpath /System/Volumes/Data/data/db而不是mongod)。我无法将localhost:3000更改为localhost:8000不知道为什么。有什么建议吗?

这是来自客户端和服务器的代码:

客户:

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/",

服务器:

    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'));

客户端以基本命令启动:npm start,服务器以命令启动:npx nodemon --exec npx babel-node src / server.js

使用程序Postman,服务器每次在app.post功能上正确获得+1投票,还添加了注释等。

javascript reactjs react-hooks reverse-proxy
1个回答
0
投票

如果您要使用

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

作为您的代理,然后在Node,您的路由不应以/开头,因为它将变为http://localhost:8000//api/articles/:name/upvote(注意多余的/

应该是

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

并且要更改默认端口号,请尝试在start文件中的package.json脚本中添加端口

"scripts": {
   "start": "PORT=3000 react-scripts start",
 }
© www.soinside.com 2019 - 2024. All rights reserved.