Using variable from client API callback in node backend - javascript

If I make a request on client side using the code below
public/foo.js
function bar() {
fetch('https://api.github.com/')
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => console.error(error))
}
how can I send the data variable to node backend?
/app.js
app.get("/", cors(), (request, response) => {
response.render('index.html');
})

It is my understanding that you are trying to fetch data from the URL that is not handled by your server-side on your client-side and send that data back to your own server-side.
On your server-side, create a new POST method:
app.post("/example", cors(), (request, response) => {
let body = request.body;
response.json(body);
})
On your client-side, send a new POST request:
function postExample(data) {
return fetch(`http://localhost:YOURPORT/example`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
}
Replace YOURPORT with your server's port. And make a call to the postExample:
function bar() {
fetch('https://api.github.com/')
.then(response => response.json())
.then(data => {
postExample(data).then(res => res.json())
.then(console.log(res));
})
.catch(error => console.error(error))
}

Related

Why is JSON data sent from server to browser undefined?

I want to make a request to my server with fetch(), and have data returned to be used in the front end app.
here is my route:
app.get('/game-data', (req, res) => {
res.json({ data: "test-data" })
})
and here is my request:
button.addEventListener('click', () => {
fetch('/game-data', {
headers: {
'accept': 'application / json',
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response)
response.json()
})
.then(myJson => {
console.log(myJson)
})
})
I can see the response object in the first console log, but response.json(), or response.text() are returning undefined.
Please help me see what I am missing!
You need to return the value to use it in another .then
.then(response => {
console.log(response)
return response.json()
})

getting error while trying to upload image to node server

Using this tutorial I want to upload images to my database, So I have this in server side:
router.post('/upload', upload.single('upload'), async (req, res) => {
try {
const incident = await Incident.findById(req.body.id)
incident.image = req.file.buffer
incident.save()
res.send()
} catch (e) {
res.status(400).send(e)
}
}, (error, req, res, next) => {
res.status(400).send({
error: error.message
})
})
And I have the binary data of the image like this in front end:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAA9tYAAQAAAADTLQAAAAAAAAAAAAAAA
In the tutorial it shows us that we can send a image via postman like this:
I used this to do the same thing as tutorial did in postman using fetch api with no luck:
const data = new FormData();
data.append("upload", image); // the image is the binary data I showed you
fetch('/accounts/upload', {
// headers: {
// 'Accept': 'application/json',
// 'Content-Type': 'application/json'
// },
method: 'post',
body: data,
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log(error));
But I get 400 (Bad Request) each time!!
How can I fix this?
I figured out that req.body is empty object like : {} So I think there is something wrong with fetch maybe
EDIT 2: Here is a log from data inside:
function uploadImage(image) {
const data = new FormData();
data.append("upload", image);
console.log(data); // added this to log the data
fetch('/accounts/upload-image', {
method: 'post',
body: data,
})
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log(error));
}
Result o the log is:

how to pass URL further in to response using fetch?

I have this fetch request a I am accepting it to
send me a statement !! if certain conditions are met
redirect me to anther page after certain time
problem is those 2 don't seem to work together if I send json resp the link is pointing to the default one future more I cannot pass the URL further down the response.
// Server side
exports.redirect = async (req, res, next) => {
//res.status(403)
res.json({ Error: 'Plase try again' })
res.redirect('/signup')
}
// Client side
fetch('/redirect', {
credentials: "same-origin",
mode: "same-origin",
method: 'POST',
//redirect: 'follow',
headers: {
"Authorization": `Bearer ${jwt}`,
"Content-Type": "application/json"
},
body: JSON.stringify(inputJSON)
})
.then(resp => {
console.log(resp.url)
return Promise.all([resp.json()])
}
).then(data => {
console.log(data);
let jsonData = data[0]
let div = document.querySelector(".form-group");
div.insertAdjacentHTML('afterend', `<div id="response">${jsonData.Error}</div>`)
//setTimeout(windows.location = data.url, 5000);
})
.catch((error) => {
console.error(error);
}).catch(err => {
if (err === "server") return
console.log(err)
})
}
})
For the general situation of when you want to pass something from an upper .then to a lower one, you'd be almost there, you just need to add the resp.url to the Promise.all array you already have:
.then(resp => {
return Promise.all([resp.json(), resp.url])
}
).then(([data, url]) => {
const div = document.querySelector(".form-group");
div.insertAdjacentHTML('afterend', `<div id="response">${data.Error}</div>`);
setTimeout(() => window.location = url, 5000);
})
But it doesn't make much sense to have a response that both has .json() and a redirect - pick one or the other. I'd recommend only a .json:
exports.redirect = async (req, res, next) => {
res.json({ Error: 'Plase try again', url: '/signup' });
}
.then(res => res.json())
.then(result => {
div.insertAdjacentHTML('afterend', `<div id="response">${result.Error}</div>`);
setTimeout(() => window.location = result.url, 5000);
})
Also make sure to pass a callback to setTimeout, and to use window.location, not windows.location.
Your final .catch(err => { block is superfluous too, it'll never be entered into and doesn't really make any sense anyway - feel free to completely remove it.

React JS Fetch from multiple URLs

I can fetch contents from my Django server with which code below.
But i need fetch from also another URL : http://127.0.0.1:8000/userpost/tagpool/
I don't know how to do. Please help.
useEffect(() => {
fetch("http://127.0.0.1:8000/api/contents/", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Token xxxxxxxxxxxxxx'
}
})
.then( resp => resp.json())
.then( resp => setFeatured(resp))
.catch( error => console.log(error))
}, [])
Use Promises chaining or Chaining
For example,
// Make a request for user.json
fetch('http://localhost/article/promise-chaining/user.json')
// Load it as json
.then(response => response.json())
// Make a request to GitHub
.then(user => fetch(`https://api.github.com/users/${user.name}`))
// Load the response as json
.then(response => response.json());

JavaScript-ReactJS problem with GET fetch request ReactJS

I'm trying to doing a basic GET request from ReactJS app to a Node.js API, but I'm getting a response with status 304. I need get a 200 status to save the response of GET in a variable. (Im running Reactjs app in port 3000 and Nodejs API in port 3300)
Node API:
app.get('/serviciosextras', async (req, res) => {
let connection;
console.log(('Servicios Extras'));
try {
connection = await oracledb.getConnection({
user: 'portafolio',
password: '123',
connectString: "localhost:1521/orcl"
});
const result = await connection.execute(
`SELECT dep.id_departamento,
se.id_servicio,
se.precio_servicio
FROM departamento_servicio_detalle dsd
JOIN departamento DEP ON (dsd.id_departamento = dep.id_departamento)
JOIN servicio_extra SE ON (dsd.id_servicio = se.id_servicio)
ORDER BY 1 ASC`
)
const resultSet = result.rows;
let lista = [];
resultSet.map(obj => {
let serviciosSchema = {
'id_departamento': obj[0],
'id_servicio': obj[1],
'precio_servicio': obj[2]
}
lista.push(serviciosSchema);
});
console.log(lista);
res.json(lista);
connection.close();
} catch (err) {
console.error(err);
}
});
GET request from Reactjs
const getExtraServices = () => {
let endpoint = `${URL}serviciosextras`;
const requestOptions = {
method: "GET",
mode: 'no-cors'
// headers: {
// "Content-Type": "application/json",
// Accept: "application/json"
// },
};
console.log(endpoint);
fetch(endpoint, requestOptions)
.then((res, err) => {
console.log(res);
})
.then(result => {
console.log('fue aqui');
console.log(result);
})
.catch(err => {
console.log('ERROR');
console.log(err);
})
}
Im calling the method from this button:(onClick={getExtraServices()})
<Fab onClick={(e) => {
e.preventDefault();
getExtraServices();
}} variant="extended">
<NavigationIcon style={{marginRight: 'theme.spacing(1)'}} />
Navigate
</Fab>
so... I'm getting this:
Firefox Console when I clicked button to call getExtraServices() res is undefined
Network console of GET request I got a response but the status is 304, so I can't get this from code. :/
Console of Nodejs API this console.log if from console.log(lista) before send the res.json(lista)
Does someone know how can I fix this? I need get the response of the GET request to charge a list in ReactJS app, but I can't because the response has body:null.
Error 304 isn't the problem.
It looks like you are missing a statement to turn your response into JSON.
Here's an example from MDN:
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
In particular:
.then(response => response.json())
In your code:
fetch(endpoint, requestOptions)
.then((res, err) => {
console.log(res); // logging res
// no data being returned here
})
.then(result => {
console.log('fue aqui');
console.log(result); // therefore result is undefined
})
.catch(err => {
console.log('ERROR');
console.log(err);
})

Categories

Resources