Hen*_*ães 5 reactjs redux mern
我正在尝试使用 MERN 堆栈创建一个项目,但遇到了此错误。我已经添加了 JSON 文件的代理,但仍然没有成功。
错误:
GET http://localhost:5000/posts net::ERR_CONNECTION_REFUSED
Run Code Online (Sandbox Code Playgroud)
我的行动:
export const getPosts = () => async (dispatch) => {
try {
const {data} = await api.fetchPosts();
dispatch({type: 'FETCH_ALL', payload: data});
} catch (error) {
console.log(error.message);
}
// const action = {type: 'FETCH_ALL', payload: []}
// dispatch(action);
}
export const createPost = (post) => async (dispatch) => {
try {
const {data} = await api.createPost(post);
dispatch({type: 'CREATE', payload: data})
} catch (error) {
console.log(error);
}
}
Run Code Online (Sandbox Code Playgroud)
我的路线/帖子:
const router = express.Router();
router.get('/', getPosts);
router.post('/', createPost);
export default router;
Run Code Online (Sandbox Code Playgroud)
服务器控制器:
export const getPosts = async (req, res) => {
try {
const postMessages = PostMessage.find();
console.log(postMessages);
res.status(200).json(postMessages);
} catch (error) {
res.status(404).json({message: error.message});
}
}
export const createPost = async (req, res) => {
const post = req.body;
const newPost = new PostMessage(post);
try {
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
res.status(409).json({message: error.message});
}
}
Run Code Online (Sandbox Code Playgroud)
服务器索引.js:
const app = express();
//MIDDLEWARE
app.use(bodyParser.json({limit: "30mb", extended: true}));
app.use(bodyParser.urlencoded({limit: "30mb", extended: true}));
app.use(cors());
app.use('/posts', postRoutes);
const PORT = process.env.PORT || 5000;
mongoose.connect(CONNECTION_URL, {useNewUrlParser:true, useUnifiedTopology: true})
.then(()=> app.listen(PORT, () => console.log('Server running on port:', PORT)))
.catch((error)=> console.log(error.message));
mongoose.set('useFindAndModify', false);
Run Code Online (Sandbox Code Playgroud)
客户端API索引:
const url = 'http://localhost:5000/posts';
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost)
Run Code Online (Sandbox Code Playgroud)
客户端.json:
{
"name": "osteoft",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:5000",
"dependencies": {
"@material-ui/core": "^4.11.2",
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"axios": "^0.21.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-file-base64": "^1.0.3",
"react-redux": "^7.2.2",
"react-scripts": "4.0.1",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"web-vitals": "^0.2.4"
},
Run Code Online (Sandbox Code Playgroud)
当我尝试配置连接时是否缺少某些内容?
小智 0
我遇到了同样的问题,经过大量搜索和再次观看教程后,我终于注意到在我的服务器上运行“$ npm start”时,我会收到一条消息说 mongodb 拒绝了连接,并且这通常是因为您使用的IP地址不在白名单中。
转到 mongodb.com/cloud/atlas,然后转到 mongodb 仪表板中的“网络访问”,然后添加新的 IP 地址,只需一个按钮即可添加您的 IP 地址。
| 归档时间: |
|
| 查看次数: |
13766 次 |
| 最近记录: |