【问题标题】:Connecting frontend to backend in MERN stack application在 MERN 堆栈应用程序中将前端连接到后端
【发布时间】:2020-08-05 11:50:18
【问题描述】:

我正在使用 MERN 堆栈开发运动跟踪器应用程序。我面临一个错误,我无法渲染它。 create-user.componet.js文件:-

import React, { Component } from 'react';
const axios=require('axios');

 class CreateUser extends Component {
    constructor(props)
    {
        super(props);

        this.onChangeUsername=this.onChangeUsername.bind(this);//even binding
        this.onSubmit = this.onSubmit.bind(this);//event binding


        this.state={
            username: '',
            
        }
    }
    onChangeUsername(e) {
        this.setState({
          username: e.target.value
        })
      }
      onSubmit(e){
        e.preventDefault() //prevents from default process and implements the lined following

        const user={
            username: this.state.username
           
        };
        console.log(user)

        //connecting the front end to the backend. On submit the username will be stored in the backend.This is done by using axios
        axios.post('http://localhost:3000/users/add',user)//accesses the route mentioned in user.js and hence connecting to the backend
        .then(res=> {
            console.log(res)
            console.log(res.data)});
        
        this.setState({
          username: ''
      })
    }
    render() {
        return (
            <div>
                <h3>Create New User</h3>
                <form onSubmit={this.onSubmit}>
                    <div className="form-group">
                    <label>Username: </label>
                <input  type="text"
                         required
                         className="form-control"
                         value={this.state.username}
                         onChange={this.onChangeUsername}/>
                        
                    </div>
                    <div className="form-group">
                        <input type="submit" value="Create User" className="btn btn-primary">
                        </input>
                    </div>
                </form>
            </div>
        )
    }
}

export default CreateUser

路由文件:-

    const router=require('express').Router();
let User=require('../models/user.model')

router.route('/').get((req,res) => {
    User.find()
    .then(users => res.json(users))
    .catch(err => res.status(400).json('Error:'+err))

});
router.post('/add', function(req, res)  {
    const username = req.body.username;
  
    const newUser = new User({username});
  
    newUser.save()
      .then(() => res.json('User added!'))
      .catch(err => res.status(400).json('Error: ' + err));
  });
module.exports=router;

错误:

POST http://localhost:3000/users/add 404 (Not Found)

在实现应用程序时,会显示上述错误,而在 insomnia(tool) 中测试时,api 工作正常。

有人可以帮忙解决这个问题吗?

【问题讨论】:

  • router.route('/') 你的问题就在这里。它应该是router.get('/', (req, res) =&gt; { .... }) .route() 用于包含路由器的文件中,而不是路由器本身。 (除非您要转发到另一个路由器,但先转发 '/' 是没有意义的,因为它会跳过路由器中的所有其他内容。)

标签: node.js reactjs mongodb express


【解决方案1】:

我认为您的路线定位错误,

在你的服务器中

router.post('/add', function(req, res)

但是在你的目标客户中

axios.post('http://localhost:3000/users/add',user)

试试改成

axios.post('http://localhost:3000/add',user)

或者尝试将服务器更改为

router.post('/users/add', function(req, res)

【讨论】:

  • 但是是路由器,这是正常的。在其他地方有一个app.use('/users', router); 虽然我仍然很想看到那个文件....
  • 你可以试试去https://localhost:3000/addhttps://localhost:3000/users/add吗?
  • 如果您正在定义app.use('/users', router);,如果您可以将其添加到代码中,那就太好了,因为我们不知道:)
  • 我正在定义 app.use('/users',router);在 server.js 文件中
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 2020-03-19
  • 2020-06-16
  • 2020-01-27
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 2023-02-14
相关资源
最近更新 更多