Axios 和 MongoDB"/>
Axios 和 MongoDB
谁能帮帮我。所以我试图将我的数据库与我的带有 axios 的反应应用程序“链接”但是当我发布用户名时它说:net::ERR_CONNECTION_REFUSED。当我不使用 nodemon 时,我的帖子请求似乎也不起作用。
顺便说一句,我使用 MongoDB 作为数据库。
代码如下:
import React, { Component } from 'react'
import axios from 'axios'
export default class createuser extends Component {
constructor(props){
super(props);
this.OnChangeUsername = this.OnChangeUsername.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
username: ""
}
}
OnChangeUsername(e){
this.setState({
username: e.target.value
});
}
onSubmit(e){
e.preventDefault();
const user = {
username: this.state.username
}
console.log(user);
axios.post('http://localhost:5000/users/add', user)
.then(res => console.log(res.data));
this.setState({
username:''
})
}
服务器/后端代码:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
mongoose.set('strictQuery', true);
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
app.listen(port,() => {
console.log(`Server running on port : ${port}`);
});
我打开了 nodemon,我可以发布新的用户名,但是当我关闭它时,我不能发布用户名,数据也不会发送到 MongoDB。
回答如下:更多推荐
Axios 和 MongoDB
发布评论