我正在使用MERN堆栈开发运动追踪器应用程序。我遇到错误,无法渲染。
[byte] * 4
文件:-
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;
在实现该应用程序时,会显示上述错误,而在insomnia(tool)中进行测试时,api可以正常工作。
有人可以帮助解决这个问题吗?
答案 0 :(得分:0)
我认为您定位的路线错误,
您的服务器中有
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)