简体   繁体   English

在 MERN 堆栈应用程序中将前端连接到后端

[英]Connecting frontend to backend in MERN stack application

I am working on an Exercise tracker application using MERN stack.我正在使用 MERN 堆栈开发运动跟踪器应用程序。 I am facing an error and I am not being able to render it.我面临一个错误,我无法渲染它。 create-user.componet.js file:- 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

route fie:-路线文件:-

    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;

error:错误:

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

On implementing the application the above error is being showed, whereas the api is working fine when tested in insomnia(tool).在实施应用程序时,会显示上述错误,而 api 在失眠(工具)中测试时工作正常。

Could someone help to render this issue?有人可以帮助解决这个问题吗?

I think you are targeting the wrong route,我认为您的目标路线错误,

in your server you have在您的服务器中,您拥有

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

But in the client you target但是在您的目标客户中

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

Try changing it to尝试将其更改为

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

Or try changing the server to或者尝试将服务器更改为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM