Express/React promise stalled - javascript

I have an Express backend server on port 5000 and react front end running on port 3000. I am trying to fetch some data from express post route and return it to front end but my Promise never resolves. It always ends up as "stalled".
util.inspect(messageList) shows my array on server console but my Promise on the front end never resolves.
I'm fetching some data server side on ComponentDidMount like below:
class Conversation extends React.Component {
state = {
conversations: [],
messages: [],
error: null,
loading: true,
input: '',
owner: 'Unassigned'
}
componentDidMount() {
const { match } = this.props
const { conversationId } = match.params
// Make a POST request to our server and pass the conversationId
this.getMessages(conversationId)
}
getMessages(conversationId) {
return fetch('/search-conversation', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ conversation: conversationId })
})
.then(res => res.json())
.then((messages) => this.setState({ messages }))
}
Server Side:
app.post('/search-conversation', (req, res) => {
conversationId = req.body.conversation
if (!conversationId) {
res.send('/error');
} else {
console.log(`Success, conv id is ${conversationId}`);
}
// call function to go get messages from API
console.log(`fetching messages for ${conversationId}`)
return fetch(endpoint)
.then((res) => res.json())
.then(({ data }) => data)
.then((data) => {
const messageList = data[0].messages.data
return messageList
})
.then((messageList) => console.log(util.inspect(messageList)))
.catch(error => console.error(`Error: ${error}`))
});
Any ideas are appreciated, thanks in advance.

You are missing res.json() call on the server side that will send response to the client:
app.post('/search-conversation', (req, res) => {
conversationId = req.body.conversation
if (!conversationId) {
res.send('/error');
} else {
console.log(`Success, conv id is ${conversationId}`);
}
// call function to go get messages from API
console.log(`fetching messages for ${conversationId}`)
return fetch(endpoint)
.then((res) => res.json())
.then(({ data }) => data)
.then((data) => {
const messageList = data[0].messages.data
res.json(messageList) // <-- sending response
})
.catch(error => console.error(`Error: ${error}`))
});

Related

why patch function not calling react native to node js

React Native
this my code. when i request for data push in database then react native App.js fetch function is not execute you can see my code and solve this bug...
this is my react native screen code where i function is not calling backend
App.js
const postdata = async () => {
const data = {cname, cphone, ccity, caddress, cemail, gender}
// 63064232cf92b07e37090e0a
const res = await fetch(`http://192.168.43.220:8000/Newcustomer/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
cname, cphone, ccity, caddress, cemail, gender
})
})
const data2 = await res.json();
console.log(data2);
if (!data2) {
window.alert('error in get data2');
}
else {
setdata(data2);
window.alert("Costomer Added")
navigation.navigate("Home")
}
}
Back End
Node js
this is my node js code. it code is properly working when i try to postman
app.js
app.patch('/Newcustomer/:id', async (req, res) => {
const _id = req.params.id;
getschema.findByIdAndUpdate(_id, {
$push: {
costomer:
{
cname: req.body.cname,
cphone: req.body.cphone,
ccity: req.body.ccity,
caddress: req.body.caddress,
cemail: req.body.cemail,
gender: req.body.gender
},
}
})
.then(data => {
res.status(201).json(data);
}).catch(err => {
console.log(err);
})
})

FETCH PATCH request returns my data as being null

app.patch('/api/todos/:id', async (req, res) => {
try {
const data = await pool.query("UPDATE todolist SET task = $1 WHERE id = $2;", [req.body.task, req.params.id])
res.json(req.body)
} catch (error) {
console.error(error.message)
}
})
I am trying to make a fetch PATCH request, but every time I do, instead of grabbing the value from the alert window and storing its value in my database, it returns null, or an empty string. Not sure why it is doing this, because it works perfectly well on Postman. Any advice would be appreciated.
import React from "react";
class UpdateBtn extends React.Component {
render() {
const updateTodo = (e, alert) => {
fetch('api/todos/' + e, {
method: 'PATCH',
header: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ task: alert })
})
.then(res => res.json())
.catch(error => console.error(error.message))
}
const handleUpdate = (e) => {
const alert = window.prompt("Update Task:")
if (alert.length === 0) {
return undefined;
}
updateTodo(e.target.id, alert)
// window.location.reload()
}
return (
<button
className="updateBtn"
id={this.props.id}
value={this.props.value}
onClick={handleUpdate}>Update</button>
)
}
}
export default UpdateBtn;

How to use fetch inside another fetch?

I have this class which is supposed to authenticate a user (in this case a moderator)
import Cookie from "universal-cookie";
import { promiseNotification, updateNotification } from "./addNotification";
const cookies = new Cookie();
class Authentication {
token;
role;
login = (username, password) => {
const id = promiseNotification("Login...")
fetch("auth/get-token", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username: username, password: password})
})
.then(res => res.json())
.then(data => {
updateNotification(id, data);
if (data.token) {
cookies.set("token", data.token);
this.setToken();
return this.setRole(); //If I understand correctly this returns a promise
}
}).then(() => window.location.replace("/mod")) //and this handles the setRole promise
.catch((error) => {alert("Error occurred login in"); console.log(error)});
}
setRole = async () => {
return fetch(`/auth/get-role/${this.token}`, {method: 'GET'}).then(res => res.json())
.then(data => this.role = data.role);
}
setToken = () => {
this.token = cookies.get("token") || "";
}
}
export default new Authentication();
When I call the login function the role and token should be set in the class instance and after it finishes it should redirect the user to the mods page. In the mods page I have this logic to prevent non moderators from accessing it.
useEffect(() => {
console.log(JSON.stringify(auth)); //This prints an empty object, meaning that none of the actions that happened in login had any effect
if (!["administrator", "moderator"].includes(auth.role)) {
createNotification("You are not a moderator", "error");
history.push("/admin-login");
}
}, []);
Why aren't any of the properties in the auth object being update?

Fetching data from firebase realtime database returns invalid json response

Here I am making a fetch request to an api -
export async function getServerSideProps(ctx) {
let id = ctx.params.id;
let userObject;
let userId;
const cookie = parseCookies(ctx);
if (cookie.auth) {
userObject = JSON.parse(cookie.auth);
userId = userObject.id;
}
if (!userId) {
return {
redirect: {
permanent: false,
destination: '/',
},
};
}
const res = await fetch(`http://localhost:3000/api/tests/${id}`);
console.log(await res.json());
const data = await res.json();
console.log(data);
// return {
// props: { product: data },
// };
return {
props: {},
};
}
Here I am reading data from firebase realtime database -
export default async (req, res) => {
const { id } = req.query;
console.log(id);
let obj;
firebase
.database()
.ref('/test/' + id)
.once('value')
.then(snapshot => {
console.log('here');
const data = snapshot.val();
obj = data;
})
.then(() => res.status(200).json(obj))
.catch(err => console.log(err));
};
Which gives me this error -
Server Error FetchError: invalid json response body at https://localhost:3000/api/tests/-MUT5-DbK6Ff6CstPSGc reason: Unexpected end of JSON input
Everything seems to work except the json response I am getting after making fetch request. I can't even console.log to see what response I am actually getting. What am I missing?
Edit - Here's my firebase database structure, where test node is root node
There is no return in your promise. That's why obj is null. Instead of then just send the response in first capture.
export default async (req, res) => {
const { id } = req.query;
console.log(id);
let obj;
firebase
.database()
.ref('/test/' + id)
.once('value')
.then(snapshot => {
console.log('here');
const data = snapshot.val();
obj = data;
res.status(200).json(obj)
})
.catch(err => console.log(err));
};

How to run a Node script

I need to be able to run a node script to delete an object from an external API. So I should be able to run this command:
node server.js Customer55555
And it should delete the object.
I have called to the API by using Axios.
const axios = require("axios");
const API = "http://dummy.restapiexample.com/api/v1/employees";
function getAllEmployees() {
axios
.get("http://dummy.restapiexample.com/api/v1/employees")
.then(response => {
// console.log(response.data);
console.log(response.status);
function filterEmployee() {
const employeeData = response.data;
employeeData.filter(employee => {
console.log(employee);
});
// console.log(employeeData);
}
filterEmployee();
})
.catch(error => {
console.log(error);
});
}
function deleteEmployee() {
axios({
method: "DELETE",
url: "http://dummy.restapiexample.com/api/v1/delete/36720",
headers: { "Content-Type": "application/json" }
})
.then(
// Observe the data keyword this time. Very important
// payload is the request body
// Do something
console.log("user deleted")
)
.catch(function(error) {
// handle error
console.log(error);
});
}
// getAllEmployees();
deleteEmployee();
I am able to get an individual object, but I need to figure out how to delete it by running the command above.
You can do something like this:
const axios = require("axios")
const API = "http://dummy.restapiexample.com/api/v1/employees"
async function getAllEmployees(filter = null) {
try {
const response = await axios.get("http://dummy.restapiexample.com/api/v1/employees")
console.log(response.status)
let employeeData = response.data
if (filter) {
// return only employees whose name contains filter.name
employeeData = employeeData.filter(({ employee_name }) => {
return employee_name.toLowerCase().indexOf(filter.name.toLowerCase()) >= 0
})
}
return employeeData
} catch(error) {
console.error(error)
return []
}
}
async function deleteEmployee({ id }) {
if (!id) {
throw new Error('You should pass a parameter')
}
try {
const response = await axios({
method: "DELETE",
url: `http://dummy.restapiexample.com/api/v1/delete/${id}`,
headers: { "Content-Type": "application/json" }
})
console.log("user deleted " + id)
} catch(error) {
// handle error
console.error(error)
}
}
async function main(params) {
const employees = await getAllEmployees({ name: params[0] || '' })
// Returns a promise to wait all delete promises
return Promise.all(employess.map(employee => deleteEmployee(employee)))
}
// process.argv contains console parameters. (https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program)
main(process.argv.slice(2)).then(() => {
// returns 0 (Success) (https://stackoverflow.com/questions/5266152/how-to-exit-in-node-js)
process.exit(0)
}).catch(() => {
// returns 1 (error)
process.exit(1)
})
You should adapt this sample to get proper filtering and error reporting.

Categories