Api works only on localhost - node.js

on my machine i get a json response when i consume my api and eveything is working fine , but the weird thing is my api not giving me data when i upload it online , i am using namecheap shared hosting , this is the result i get when try to consume api
this is my index.js code
app.get("/project/index/login", (req, res) => { (async () => {
try {
await client.login();
res.send("Login successful!");
} catch (err) {
res.send("Login failed!");
} })(); });
app.get("/project/index/user/:id", (req, res) => {
const id = req.params.id; (async () => {
try{
const data = await client.getInfo({ id: id })
res.json(data.data);
}catch(error){
res.send(error);
}
})(); });
app.listen(port, () => {
console.log(`Listening on port http://localhost:${port}...`);
});

It's probably because your API server is running only on localhost. Check your API server!. You must run the API server which has a domain.

Related

Hide api using expressjs and react

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)

React.js + Node.js - Error when responding from server. "UnhandledPromiseRejectionWarning: Error: Request failed with status code 304"

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.

Problems using React JS and WebSockets

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)
}
});

firebase once('value') function on database not response

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

How to start an Express server in best practice?

I have an Express REST API server written in TypeScript.
At first, I started server like this -
const initServer = async() => {
await connectDb();
await server.listen(secrets.port, secrets.hostname, () => {
logger.info(
`Running server at http://${secrets.hostname}:${secrets.port} in ${
secrets.env
} env and API version is ${secrets.apiVersion}`
);
});
}
initServer().catch(error => logger.error(`Init server went wrong with: ${error}`));
Then I read a blog post suggesting to use .then().catch() -
async function initServer() {
// Connect the database first
await connectDb()
.then(() =>
// then start the server
server.listen(secrets.port, secrets.hostname, () => {
logger.info(
`Running server at http://${secrets.hostname}:${secrets.port} in ${
secrets.env
} env and API version is ${secrets.apiVersion}`
);
})
)
.catch(err => {
logger.error(`Initializing server went wrong with: ${err}`);
process.exit(1);
});
}
Then I read another blog post saying "catch the error first" -
async function initServer() {
// Connect the database first
await connectDb()
// then start the server
.then(() => server.listen(secrets.port, secrets.hostname))
.catch(err => {
logger.error(`Initializing server went wrong with: ${err}`);
process.exit(1);
})
// then announce the server info
.finally(() => {
logger.info(
`Running server at http://${secrets.hostname}:${secrets.port} in ${
secrets.env
} env and API version is ${secrets.apiVersion}`
);
});
}
But I feel like I'm not doing it right. Please educate me what I'm doing wrong.
How should I start the server?

Resources