[英]AxiosError : Failed to load resource: net::ERR_CONNECTION_REFUSED
I am still learning react and I am building an app with MERN Stack.我还在学习反应,我正在用 MERN Stack 构建一个应用程序。 I tried submitting a post from the form, which is supposed to send data to the MongoDB Atlas database and also render the post on the page.
我尝试从表单提交帖子,该表单应该将数据发送到 MongoDB Atlas 数据库,并在页面上呈现帖子。 But no data is sent to the database, nor is it rendered on the page.
但是没有数据发送到数据库,也没有呈现在页面上。 I don't really know where the problem is coming from, but I am having an axios error and a 404 error on the Chrome browser console.
我真的不知道问题出在哪里,但我在 Chrome 浏览器控制台上遇到 axios 错误和 404 错误。 I don't know if Axios is not connected to the backend or if there is a problem with my codes.
不知道是Axios没有连接到后端还是我的代码有问题。
Form.js表单.js
import React, { useState, useEffect } from 'react';
import { TextField, Button, Typography, Paper } from '@material-ui/core';
import FileBase from 'react-file-base64';
import { useDispatch, useSelector } from 'react-redux';
import useStyles from './styles';
import { createPost, updatePost } from '../../actions/posts';
//GET POST CUURENT ID
const Form = ({ currentId, setCurrentId }) => {
const [postData, setPostData] = useState({creator: '', title: '', message: '', tags: '', selectedFile: ''});
const post = useSelector((state) => currentId ? state.posts.find((p) => p._id === currentId) : null);
const classes = useStyles();
const dispatch = useDispatch();
useEffect(() => {
if(post) setPostData(post);
}, [post])
const handleSubmit = (e) => {
e.preventDefault();
if(currentId) {
dispatch(updatePost(currentId, postData));
} else {
dispatch(createPost(postData));
}
clear();
}
const clear = () => {
setCurrentId(null);
setPostData({creator: '', title: '', message: '', tags: '', selectedFile: ''});
}
return (
<Paper className={classes.paper}>
<form autoComplete='off' noValidate className={`${classes.root} ${classes.form}`} onSubmit={handleSubmit}>
<Typography variant='h6'>{ currentId ? 'Edit' : 'Create' } Your Expressions</Typography>
<TextField name='creator' variant='outlined' label='Creator' fullWidth value={postData.creator} onChange={(e) => setPostData({ ...postData, creator: e.target.value })} />
<TextField name='title' variant='outlined' label='Title' fullWidth value={postData.title} onChange={(e) => setPostData({ ...postData, title: e.target.value })} />
<TextField name='message' variant='outlined' label='Message' fullWidth value={postData.message} onChange={(e) => setPostData({ ...postData, message: e.target.value })} />
<TextField name='tags' variant='outlined' label='Tags' fullWidth value={postData.tags} onChange={(e) => setPostData({ ...postData, tags: e.target.value })} />
<div className={classes.fileInput}><FileBase type="file"multiple={false} onDone={({base64}) => setPostData({ ...postData, selectedFile: base64 })} />
</div>
<Button className={classes.buttonSubmit} variant='contained' color='primary' size='large' type='submit' fullWidth>Submit</Button>
<Button variant='outlined' color='primary' size='large' onClick={clear} fullWidth>Clear</Button>
</form>
</Paper>
);
}
export default Form;
Server/index.js服务器/index.js
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js'
const app = express();
app.use('/posts', postRoutes);
app.use(bodyParser.json({ limit: "30mb", extended: true}));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true}));
app.use(cors());
app.use('/posts', postRoutes);
const CONNECTION_URL = 'mongodb+srv://Akan-
modanwealth:aakkaann@cluster0.jvfdwah.mongodb.net/?retryWrites=true&w=majority';
const PORT = process.env.PORT || 5000;
mongoose.connect(CONNECTION_URL).then(()=>{console.log('...')})
.then(() => app.listen(PORT, () => console.log('Server running on port:
${PORT}')))
.catch((error) => console.log(error.message));
App.js应用程序.js
import React, { useState, useEffect } from 'react';
import { Container, AppBar, Typography, Grow, Grid } from '@material-ui/core';
import { useDispatch } from 'react-redux';
import { getPosts } from './actions/posts';
import Posts from './components/Posts/Posts';
import Form from './components/Form/Form';
import expressions from './images/expressions.jpg';
import useStyles from './styles';
const App = () => {
const [currentId, setCurrentId] = useState(null);
const classes = useStyles();
const dispatch = useDispatch();
useEffect(() => {
dispatch(getPosts);
}, [currentId, dispatch]);
return (
<Container maxWidth="lg">
<AppBar className={classes.appBar} position="static" >
<Typography className={classes.heading} variant="h2" align="center">Expressions</Typography>
<img className={classes.image} src={expressions} alt="expressions" height="80" width="60" />
</AppBar>
<Grow in>
<Container>
<Grid container justifyContent="space-between" alignItems="stretch" spacing={3}>
<Grid item xs={12} sm={7}>
<Posts setCurrentId={setCurrentId} />
</Grid>
<Grid item xs={12} sm={4}>
<Form currentId={currentId} setCurrentId={setCurrentId} />
</Grid>
</Grid>
</Container>
</Grow>
</Container>
);
}
export default App;
api/index.js api/index.js
import axios from 'axios';
const url = 'http://localhost:5000/posts';
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatedPost) => axios.patch(`${url}/${id}`,
updatedPost);
routes/posts.js路线/posts.js
import express from 'express';
import { getPosts, createPost, updatePost} from
'../controllers/posts.js';
const router = express.Router();
router.get('/', getPosts);
router.get('/', createPost);
router.patch('/:id', updatePost)
export default router;
So there are a couple of things.所以有几件事。 First, you may have exposed your password in your MongoDB URI, so I'd go and change that immediately.
首先,您可能在 MongoDB URI 中暴露了您的密码,所以我会使用 go 并立即更改它。 Second, is there a reason you're running
app.use("/posts", postRoutes);
其次,您运行
app.use("/posts", postRoutes);
是否有原因? twice?两次?
Lastly, it looks like you're posting to /posts
, but you're not specifying a route after that.最后,看起来您正在发布到
/posts
,但之后您没有指定路线。 You didn't share your routes, but from the looks of it /posts
uses all routes in your routes folder.您没有共享您的路线,但从它的外观
/posts
使用您的路线文件夹中的所有路线。 You need to give a specific route, like /posts/create
or something.你需要给出一个特定的路线,比如
/posts/create
什么的。 Otherwise you're just saying making a POST request to the object with all your middleware and node.js doesn't know which middleware to use.否则,您只是说使用所有中间件向 object 发出 POST 请求,而 node.js 不知道要使用哪个中间件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.