Axios 和 MongoDB

编程入门 行业动态 更新时间:2024-10-09 01:23:25

<a href=https://www.elefans.com/category/jswz/34/1771419.html style=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

本文发布于:2024-05-13 13:54:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759644.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Axios   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!