I'm using MERN stack for a project. I want to hide my api endpoints on the frontend when I call them. I'm now making a request from React like so:
useEffect(() => {
axios
.get("https://MY_API_URL/posts") // MY_API_URL is the url that I want to hide
.then((res) => {
dispatch(setCurrentUser(res.data));
})
.catch((err) => {
console.log(err);
});
});
This is how I'm GETing the posts from the expressjs:
controllers/posts.js
const Post = require("../models/post");
const getPosts = async (req, res) => {
try {
const post = await Post.find();
res.status(200).json(post);
} catch (err) {
res.status(404).json({ message: err });
}
};
I want to make the request to the url from the backend so that my API is hidden in the client.
This is what I have tried in the frontend:
useEffect(() => {
axios
.get("http://localhost:3000/posts")
.then((res) => {
dispatch(setCurrentUser(res.data));
})
.catch((err) => {
console.log(err);
});
});
And my backend now looks like this but it doesn't work. I also have removed the Posts.find() inside the request, I'm not sure if it is still necessary or how am I going to use this?
controllers/posts.js
const getPosts = async (req, res) => {
try {
const response = await axios.get(
"https://MY_API_URL/posts"
);
const posts = response.data;
console.log(posts);
res.status(200).json(posts);
} catch (err) {
res.status(404).json({ message: err });
}
};
On localhost it works fine, but when I push my code to github and deploy it, it doesn't work on the deployed version then in the localhost it also stops working.
Error message on console:
GET http://localhost:3000/posts 404 (Not Found)
Related
I have the below route created in my application which calls another API for data:
newsr.get('/news', async (req, res) => {
var category = req.params.category;
try {
var url = 'http://newsapi.org/v2/top-headlines?country=in&category=general' + '&apiKey=36f3e29b704f41339af8439dc1228334';
const news_get = await axios.get(url)
res.status(200).json().render('category', { articles: news_get.data.articles })
// return res.status(200).json(news_get)
} catch (error) {
if (error.response) {
console.log(error)
}
}
})
The problem is, when I call the get API http://localhost:8080/news. I do not get the response from the external API. Can you please suggest what to do?
As the title suggest, I get a weird error when responding with data from my server.
In homepage.js (which I want to load after loggin in) I have this request to the server to get the posts and then set the posts to the response.
useEffect(() => {
//userService.getDashboard() === Axios.get('http://localhost:3001/homepage')
userService.getDashboard().then((response) => {
setListOfPosts(response)
});
}, []);
This request first goes to the homepage.js, which further sends a request to getPosts, like so:
const headers = req.headers;
const getPosts = Axios.get('http://localhost:3001/getPosts', {headers: headers});
getPosts.catch((response) => {
//NEVER GET ANY RESPONSE???
console.log('Error in homepage.js')
//res.send(response);
});
getPosts.then((response) => {
//NEVER GET ANY RESPONSE???
res.send(response.data);
});
And lastly in the chain I have the getPosts router which does:
router.get('/', authenticateToken, async (req, res) => {
await db.query('SELECT * FROM posts',
(err, result) => {
if (err) {
console.log('HELLO FROM ERROR')
res.send({errorMessage: err});
} else {
console.log(result)
res.send(result);
}
});
});
So I can confirm that after every request to homepage I get all the way to getPosts() and the database query always works fine and goes into the result where "console.log(result)" lies and I can confirm that the result is indeed all the posts. The weird stuff happens when I'm sending back the data. So from getPosts() I'm obviously doing a res.send(result) which sends the data back to homepage.js. But this is when I get the error "UnhandledPromiseRejectionWarning: Error: Request failed with status code 304"
Any idea why?
you should not use res.send inside the .then of axios
this code works for me
useEffect(() => {
getPosts.then((response) => {
console.log("inside getPosts.then ");
console.log(response);
});
and this is my controller file to send request to backend:
const axios = require("axios");
export const getPosts = axios.get("http://localhost:5000/tasks/taskscheck");
getPosts.catch((response) => {
console.log("Error in homepage.js");
});
getPosts.then((response) => {
console.log("inside then get posts");
console.log(response);
});
I have tasks project and I can see in the response all my tasks.
I am learning about these technologies (React JS, Node, WebSockets) and working on a project that uses websockets to display information on graphs in real time.
I have a state in my component that stores an array of objects with different attributes.
When I make a POST request to my server the record is saved in the database (Made in PostgreSQL) and I notify the client to do the update
My problem is that when I refresh the page it stops working and I need to restart the server to be able to see the changes in the graph again.
SERVER
io.on('connection', client => {
app.post("/registros/nuevo", async (req, res) => {
try {
let insertar = await pool.query(`INSERT INTO registro
(fecha, hora, temperatura, presion, humedad, viento, viento_max, radiacion, precipitacion)
VALUES
('${req.body.fecha}', '${req.body.hora}', ${req.body.temperatura}, ${req.body.presion},
${req.body.humedad}, ${req.body.viento}, ${req.body.viento_max}, ${req.body.radiacion},
${req.body.precipitacion});`).then(() => { client.emit('new: data', 'updated') });
res.json({ message: "Recibido" });
} catch (err) {
console.error(err.message);
}
});
});
CLIENT
const [data, setData] = useState([])
const getData = async () => {
try {
const response = await fetch("http://localhost:5000/registros");
const jsonData = await response.json();
setData(jsonData);
setCurrent(jsonData[jsonData.length - 1])
} catch (err) {
console.error(err.message)
}
};
useEffect(() => {
getData()
}, [])
useEffect(() =>{
socket.on('new: data', (c) =>{
console.log(c)
getData()
})
}, []);
I know that my code isn't the best, and thank u for ur help
I got the solution, my mistake was put the request inside of socket body
app.post("/registros/nuevo", async (req, res) => {
try {
let insertar = await pool.query(`INSERT INTO registro
(fecha, hora, temperatura, presion, humedad, viento, viento_max, radiacion, precipitacion)
VALUES
('${req.body.fecha}', '${req.body.hora}', ${req.body.temperatura}, ${req.body.presion}, ${req.body.humedad}, ${req.body.viento}, ${req.body.viento_max}, ${req.body.radiacion}, ${req.body.precipitacion});`)
io.emit('new: data', 'Actualizado')
res.sendStatus(204)
} catch (err) {
res.sendStatus(500)
}
});
it does give me back the id , but it is not deleting it from the mongodb collection & frontend list , I keep getting a 404 error on the network dev tools tab....
NodeJS
app.delete("/showlist-fromdb/:id", async (req, res) => {
try {
let uid = req.params.id.toString();
List.deleteOne({ _id: uid });
} catch (err) {
console.error(err);
}
});
React:
export const deleteListing = async (idHolder) =>{
/**DELETE METHOD */
const options = {
url: `http://localhost:5001/showlist-fromdb/:id${idHolder}`,
method: 'DELETE',
// data: idHolder
};
axios(options)
.then(response => {
console.log('A listing got deleted!')
}).catch((err)=>{console.log(err)})
// axios.delete(`http://localhost:5001/showlist-fromdb/:id${idHolder}`)
}
figured out the problem i forgot to add await before the delete command, thanks everyone
I would happy for your help
I'm trying to use firebase on nodejs server.
after initial configurations I build a rest on node server that used to fetch data from firebase database
Here is the first version of the code
app.get('/api/users/:id', (req,res) =>{
const usersRef = firebase.database().ref('users');
usersRef.once('value')
.then((snapshot) => {
console.log(snapshot);
res.status(200).send(snapshot.val())
})
.catch((error) => {
console.log(error);
res.status(404).send(error.message)
})
}))
I've checked the route with postman and found that I didn't received any response from that route
I've check with logs that the route received the request and I found that I must create async call to database, so, I created middleware
And here is the new version of code:
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
app.get('/api/users/:id', asyncMiddleware(async (req,res,nex) =>{
const usersRef = firebase.database().ref('users');
await usersRef.once('value')
.then((snapshot) => {
console.log(snapshot);
res.status(200).send(snapshot.val())
})
.catch((error) => {
console.log(error);
res.status(404).send(error.message)
})
}))
But the problem continue even after the changes.
So I found that the reason for the problem is because the 'once' function stack when he tried to fetch data from firebase and not return any response.
I would really like to your help here
thanks
I guess it has to do with the way you handle the asynchronous requests. Try the code below and let's see if we'll get any luck.
const fetchUsers = () => new Promise((resolve, reject) => {
try{
const usersRef = firebase.database().ref('users')
usersRef.once('value', (snapShot) => {
resolve(snapShot)
})
}catch(err){
reject(err)
}
})
app.get('/api/users/:id', async (req,res) =>{
const users = await fetchUsers()
/**
* clean the users response
* and respond with data
*/
res
.status(200)
.json({
data: users //cleaned
})
}))
So, After Investigate I found a solution for this problem.
I've used axios on server send request by using REST API of firebase
https://firebase.google.com/docs/reference/rest/database