【发布时间】: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) => { .... }).route() 用于包含路由器的文件中,而不是路由器本身。 (除非您要转发到另一个路由器,但先转发 '/' 是没有意义的,因为它会跳过路由器中的所有其他内容。)
标签: node.js reactjs mongodb express