Failed to load resource: net::ERR_CONNECTION_REFUSED getting this error. an the another one is Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)
plaese tell me more about this how do i fix this bug.
Client side app.js file
import { useState } from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [foodname,setFoodName] = useState("");
const [days,setDays] = useState(0);
const addToList = () =>{
Axios.post("http://localhost:3001/insert", {
foodname: foodname,
days: days
});
};
return (
<div className="App">
<h1>CRUD APP WITH MERN</h1>
<label>Enter Food Name:</label>
<input
type="text"
onChange={(event) => {
setFoodName(event.target.value);
}}/>
<label>Days Since I Ate:</label>
<input
type="number"
onChange={(event) => {
setDays(event.target.value);
}}/>
<button onClick={addToList}>Add to List</button>
</div>
);
}
export default App;
Server side index.js file
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const FoodModel = require("./models/Food");
app.use(express.json());
app.use(cors());
mongoose.connect("mongodb+srv://crudop:crudop#crud.jmbry.mongodb.net/food?retryWrites=true&w=majority",{
useNewUrlParser: true,
useUnifiedTopology: true
});
app.post('/insert',async (req,res)=>{
const FoodName = req.body.foodname;
const days = req.body.days;
const food = new FoodModel({foodname: FoodName, daysSinceIAte:days});
try{
await food.save();
res.send("inserted");
}
catch(err){
console.log(err);
}
});
app.listen(3001, ()=>{
console.log("server is running on port 3001...");
})
wait for MongoDB connection
after that start listening onto the port
mongoose
.connect(DB_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
.then((result) => {
app.listen(3001, () => {
console.log("Server started on port 3001");
});
})
.catch((err) => console.log(err));
Related
I'm developing a fullstack realtime chat project using socket io. In theory it's working, but not the way I'd like. There are two problems.
1 - On my server, I store the messages in an array and send them to react through useEffect, but even so, every time I refresh the page, the previous messages only appear when I send a new message.
2 - I can only view the messages I send when I receive a message. I mean, opening two browsers with chat and testing...
Browser 1 = I send a lot of messages and Browser 2 sees them all, but I don't see my messages until Browser 2 sends me a message, so his message appears and all the messages I sent.
server
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const dotenv = require('dotenv')
const app = express();
const mongoose = require('mongoose');
const http = require('http');
const server = http.createServer(app);
const { Server } = require('socket.io');
const io = new Server(server, {
cors: {
origin: ['http://localhost:3000'],
}
});
dotenv.config();
const nameRoutes = require('./routes/nameRoutes');
app.use(express.json());
app.use(cors());
app.use(bodyParser());
app.use('/name', nameRoutes);
app.use('/', (req, res) => {
res.status(200).json({ msg: 'API IS ALIVE!' });
})
let messages = []
io.on('connection', (socket) => {
socket.on('send-message', (data) => {
messages.push(data);
socket.broadcast.emit('message-from-server', messages);
console.log(messages);
})
});
async function connection () {
const uri = process.env.MONGO_URI;
const port = process.env.PORT;
try {
await mongoose.connect(uri);
console.log('Connected to database');
server.listen(port, () => {
console.log(`Listening on port ${port}`)
});
} catch (err) {
console.log(err);
}
}
connection();
module.exports = app;
frontend
import * as C from './styles';
import { io } from 'socket.io-client';
import { useNavigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
const Chat = () => {
const navigate = useNavigate();
const [message, setMessage] = useState('');
const [chatMessages, setChatMessages] = useState([]);
const [socket, setSocket] = useState(null);
useEffect(() => {
setSocket(io("http://localhost:3010"));
}, []);
useEffect(() => {
if (socket) {
socket.on('message-from-server', (data) => {
setChatMessages(data);
})
}
}, [socket])
const handleSendMessage = () => {
if (message) {
socket.emit('send-message', { message });
setMessage('');
}
}
const handleExitChat = () => {
navigate('/');
}
return (
<C.Container>
<C.MessagesChat>
<h2>Messages</h2>
</C.MessagesChat>
{chatMessages.map(text => {
return (
<C.Messages>
<p>{text.message}</p>
</C.Messages>
)
})}
<C.MessageText>
<textarea
name=""
id=""
cols="30"
rows="10"
placeholder='Digite sua mensagem...'
value={message}
onChange={(e) => setMessage(e.target.value)}
></textarea>
<button onClick={handleSendMessage}>Enviar</button>
</C.MessageText>
<C.Logout>
<button onClick={handleExitChat}>Abandonar a conversa</button>
<button onClick={handleExitChat}>Destruir a conversa</button>
</C.Logout>
</C.Container>
)
}
export default Chat;
I am following a tutorial in order to understand how to connect the express routes that I have written to a react app.
The code, as I best understand it, is supposed to work as follows
App.js
import axios from "axios"
import React, { useState } from "react"
import "./App.css"
function App() {
const [ name, setName ] = useState("")
const [ home, setHome ] = useState("")
useEffect(() => {
axios.get("http://localhost:4000/home").then(function(response) {
setHome(response.data)
})
}, [])
async function postName(e) {
e.preventDefault()
try {
await axios.post("http://localhost:4000/post_name", {
name
})
} catch (error) {
console.error(error)
}
}
return (
<div className="App">
<form onSubmit={postName}>
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
<button type="submit">Send Name</button>
</form>
{home}
</div>
)
}
export default App
the body above has a submit form that takes text inputted by the user, then on submit the form calls the async function postName. postName utilizes the built in function axios.post which fetches the url corresponding to the url/express_route my index.js is using and passes in the object name which I created at the top of the function in my useState.
In the index.js
const express = require("express")
const app = express()
const port = 4000
const cors = require("cors")
// npm init
// npm i express cors nodemon
// they add a handy req.body object to our req,
// containing a Javascript
// object representing the payload sent with the request
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors())
app.get("/", cors(), async (req, res) => {
res.send("This is working")
})
app.get("/home", cors(), async (req, res) => {
res.send("This is the data for the home page")
})
app.post("/post_name", async (req, res) => {
let { name } = req.body
console.log(name)
})
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`)
})
we have an async function app.post which is meant to deal with the express route we set up in the axios function and then prints the submitted name to console. I am able to get both of them running. I have nodemon, express axios and cors installed to allow for communication between the different urls. What am I missing why is this happening.
hey I'm very new to MERN stack and I'm having an issue posting data with Axios and express. I might have understood this wrong but here goes my problem. I have a form on a page which I'm trying to submit data from to the backend where I then console log it. the page is a component which contains the onsubmit function, which sends a post request to server.js which then console.logs it, however I've been getting an ERROR 404 on submitting. Dependencies should be installed correctly
This is my on submit function
onSubmit(e) {
e.preventDefault();
console.log(`Form submitted:`);
console.log(` ${this.state.searchquery}`);
const newSearchQuery = {
searchquery: this.state.searchquery,
};
axios.post('http://localhost:3000/', newSearchQuery)
.then(res => console.log(res.data)).then(
(response) => { console.log(response) },
(error) => { console.log(error) }
);;
this.setState({
searchquery: '',
})
}
this is the server.js file
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const todoRoutes = express.Router();
const PORT = 3000;
app.use(cors());
app.use(bodyParser.json());
todoRoutes.route('/').post(function(req, res) {
console.log(req.body);
});
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});```
App is not configured to use the routes and that's why it throws a 404.
Use this line after todoRoutes.Route():
app.use(todoRoutes);
app.use() is used to register middlewares to the main node app. Since you are using router express middleware, you need to register it as well.
EDIT: This works for me. In case you want the complete code:
ReactJS:
import React from "react";
import axios from 'axios';
class App extends React.Component {
constructor() {
super();
this.state = {
searchquery: ''
};
}
handleChange = (e) => {
this.setState({ searchquery: e.target.value });
}
onSubmit = (e) => {
e.preventDefault();
console.log(`Form submitted:`);
console.log(` ${this.state.searchquery}`);
const newSearchQuery = {
searchquery: this.state.searchquery,
};
axios.post('http://localhost:3000/', newSearchQuery)
.then(res => console.log(res.data)).then(
(response) => { console.log(response) },
(error) => { console.log(error) }
);;
this.setState({
searchquery: '',
})
}
render() {
return (<form onSubmit={this.onSubmit}>
<input type="text" value={this.state.searchquery} name="searchquery" id="searchquery" onChange={this.handleChange} />
<button type="submit">Submit</button>
</form>);
}
}
export default App;
Express code:
const express = require("express");
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const todoRoutes = express.Router();
const PORT = 3000;
app.use(cors());
app.use(bodyParser.json());
todoRoutes.route('/').post(function(req, res) {
console.log(req.body);
});
app.use(todoRoutes);
app.listen(PORT, function() {
console.log("Server is running on Port: " + PORT);
});
I have created an express server in my server.js file, and I export app from it.
//server.js
require("dotenv").config();
const express = require("express");
const app = express();
const connectToDb = require("./connectToDb")
connectToDb().catch(console.dir)
app.use((req, res) => {
res.status(404).send("unable to find");
});
module.exports = app
I import app from server.js in the connectToDb.js file
//connectToDb.js
const app = require("./server")
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const port = process.env.PORT || 3000;
const connectToDb = async () =>{
try {
await client.connect();
console.log("Connected correctly to server");
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
} catch (err) {
console.log(err.stack);
} finally {
await client.close();
console.log("hello")
}
}
module.exports = connectToDb
It connects succesfully to the database, but when it reaches app.listen it gives me this error: TypeError: app.listen is not a function. I don't know why it gives me an error because I have exported app. What am I doing wrong?
That's because you have a cyclic dependency. The two files import each other, and inside server.js you make a call immediately on load. In the moment you call connectToDb inside of server.js, the server.js file has not fully executed yet and hence the module export has not yet happened. Either way it's something you should try to avoid (cyclic dependencies).
Just resolve the cycle by passing the app to the connectToDb function as a parameter instead of importing it:
//server.js
require("dotenv").config();
const express = require("express");
const app = express();
const connectToDb = require("./connectToDb")
connectToDb(app).catch(console.dir)
app.use((req, res) => {
res.status(404).send("unable to find");
});
module.exports = app
// connectToDb.js
const MongoClient = require("mongodb").MongoClient;
const client = new MongoClient(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const port = process.env.PORT || 3000;
const connectToDb = async (app) =>{
try {
await client.connect();
console.log("Connected correctly to server");
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
} catch (err) {
console.log(err.stack);
} finally {
await client.close();
console.log("hello")
}
}
module.exports = connectToDb
I am trying to call my vue api service via axios. However, it does not work at all and I am getting Network Error message on my browser console.
Could anyone advice what I did wrong? Below I have attached my code from by the client and server side.
error
api.js
const axios = require('axios')
export default () => {
return axios.create({
baseURL: 'http://localhost:1991'
})
}
api_metrics.js
import api from '#/services/api.js'
const url = api() + '/api/metrics/'
export default {
getIpAddress () {
console.log(url)
return api().get(url)
}
}
express_server.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
// middleware
app.use(cors())
const metrics = require('./routes/api/metrics')
app.use('/api/metrics', metrics)
const port = process.env.PORT || 1991
app.listen(port, ()=>{
console.log(`server running on port ${port}`)
})
server_api.js
const express = require('express')
const router = express.Router()
router.get('/', (req,res)=>{
console.log('getIpAddress ')
res.send('"metrics"')
})
module.exports = router
home.vue
<template>
<p>Home</p>
</template>
<script>
export default {
data: () => ({
this.user_information = []
}),
async created () {
try {
this.user_information = await
apiService.getIpAddress()
console.log(this.user_information)
} catch (err) {
console.log(err.message)
}
}
}
</script>