如何解决GET http://localhost:5000/posts net::ERR_CONNECTION_REFUSED
我正在尝试使用 MERN 堆栈创建项目,但遇到此错误。我已经添加了代理来处理 JSON 文件,但仍然没有运气。
错误:
GET http://localhost:5000/posts net::ERR_CONNECTION_REFUSED
我的行为:
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);
}
}
我的路线/帖子:
const router = express.Router();
router.get('/',getPosts);
router.post('/',createPost);
export default router;
服务器控制器:
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});
}
}
服务器 index.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);
客户端 API 索引:
const url = 'http://localhost:5000/posts';
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url,newPost)
client.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"
},
我尝试配置连接时是否遗漏了什么?
解决方法
我遇到了同样的问题,经过大量搜索单步执行并再次观看教程后,我终于注意到在我的服务器上运行“$ npm start”时,我会收到一条消息,说 mongodb 拒绝了连接,这通常是因为您使用的 IP 地址未列入白名单。
转到 mongodb.com/cloud/atlas,然后转到 mongodb 仪表板中的“网络访问”,然后添加一个新的 ip 地址,只需一个按钮即可添加您的 ip 地址。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。