我一直收到POSThttps://localhost:5000/users/addnet::ERR_CONNECTION



我正在使用MERN堆栈开发一个运动跟踪器应用程序。我有一个react JS组件,它允许我在按下提交按钮后向数据库添加一个新用户。我使用axios将http请求从前端发送到后端的服务器端点。然而,我不断得到这个错误

POSThttps://localhost:5000/users/addnet::ERR_CONNECTION_REFUSED未捕获(承诺中(错误:createError处的网络错误(0.chunk.js:971(在XMLHttpRequest.handleError(0.chuck.js:466(

这是我的服务器端代码

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
//mongoose is whats going to help us connect to our mongoDB database

require('dotenv').config();
//this configures si we can have our environment variables in the dotenv file
const app = express();
const port = process.env.PORT || 5000;
//this is how we will create our express server 
app.use(cors());
app.use(express.json());
//this is our middle ware this will allopw us to parse json
// cause the server will be sending s=and receiving json
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology:true});
//uri is where database is stored
const connection = mongoose.connection;
connection.once('open',() =>{
console.log("MongoDB database connection established successfully");
});
//once connection is open its going to log the message
const exercisesRouter = require('./routes/excercises');
const usersRouter = require('./routes/users');
//importing 
app.use('/excercises',exercisesRouter);
app.use('/users',usersRouter);
//use files
//whenever somebody goes to route url and put /excersies at the end it will show
//everything in excercises and the same for users

app.listen(port,()=>{
console.log('Server is running on port: ' + port);
});
//this is what starts the server. It start listening to a certain port

这是我的提交功能

onSubmit(e){
e.preventDefault(); //prevents default html form behaviour taking place
const user = {
username: this.state.username,
};
console.log(user);
//sending user data to the backend with post request
//check user.js file in routes its sending a post request to the user.add api
axios.post('https://localhost:5000/users/add',user)
.then(res => console.log(res.data));
this.setState({
username: ''
});
}

这是我的路线

router.route('/add').post((req,res) => {
const username = req.body.username;
const newUser = new User({username});
//using unsername to create new user
newUser.save()
.then(() => res.json('User added')) //after user saved to DB return user added message
.catch(err => res.status(400).json('Error ' + err)); //if there is an error return error
});

检查您的后端是否也在端口5000上运行,您需要启动后端

我也学习了本教程,您必须启动后端和前端。问题是前端只在运行,这就是为什么你可以看到一切(不确定他是如何管理的(,但我不得不拉起一个终端,用->npm启动和后端带有->单独的终端选项卡上的nodemon服务器

兄弟,我想你只是在地址上犯了一个小错误https://localhost:5000/users/add不是https将其更改为http,它将解决您的问题你的地址是http://localhost:5000/users/add

相关内容

最新更新