无法在响应中发出post请求(axios,前端和节点服务器在不同的端口上运行)

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

所以我有一个我正在研究的mern堆栈。我正在从我的SignupForm组件发出一个帖子请求。

  handleSubmit(event) {
        event.preventDefault()
        // TODO - validate!
        axios
            .post('/auth/signup', {
                username: this.state.username,
                password: this.state.password
            })

    }

到我的routes文件夹中的post处理程序

router.post('/signup', (req, res) => {
    //const { username, password } = req.body

    console.log('signup route hit in auth folder')
    res.end()
    // ADD VALIDATION

})

当我使用邮递员到这个路由localhost:8080 / auth / signup我得到正确的控制台日志,但我的前端是在localhost:3000上运行

我一直收到这个错误

VM1951:1 POST http://localhost:3000/auth/signup 404 (Not Found)
(anonymous) @ VM1951:1
createError.js:16 Uncaught (in promise) Error: Request failed with status code 404
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

如何将前端和后端端口组合成一个完整的堆栈应用程序?

谢谢

node.js reactjs
2个回答
2
投票

来自客户端的请求将转到同一主机,因为路由以斜杠开头(\

你提交的句柄应该是这样的

  handleSubmit(event) {
        event.preventDefault()
        // TODO - validate!
        axios
            .post('http://localhost:8080/auth/signup', {
                username: this.state.username,
                password: this.state.password
            })
    }

© www.soinside.com 2019 - 2024. All rights reserved.