how to pass URL further in to response using fetch? - javascript

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.

Related

API inserting "undefined" into path in my React App

I'm sure I probably have something simple to fix, but have tried and tried and cannot find it. I have several API calls that are working just fine. But I have made a new one, which I made by copy and pasting ones that worked, and just changing values and names. But this new one, gives me a 500 error.
The API path should be:
"http://localhost:3000/billingcalculator/create"
Instead, it is:
"http://localhost:3000/undefined/billingcalculator/create" <-- where is the undefined coming from?
It gives this error:
PUT http://localhost:3000/undefined/billingcalculator/create 500 (Internal Server Error)
It references the line in the call that says throw new Error() ; but I don't see what's wrong with that. I use that exact same code all over the place and it works fine everywhere else.
Call that works perfectly:
createHCA() {
fetch(API_URL + `/hca/create`, {
method: "PUT",
body: JSON.stringify({
client: this.state.client,
short: this.state.short,
}),
headers: { "Content-Type": "application/json" },
})
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
.then(() => this.getHCAid())
.then(() => this.getAllHCAs());
this.setState({ showHide: false});
}
And this is the call that creates the error and cannot reach my API routes:
createBillProject() {
fetch(API_URL + `/billingcalculator/create`, {
method: "PUT",
body: JSON.stringify({
client: this.state.client,
source: this.state.source,
projectName: this.state.projectName
}),
headers: { "Content-Type": "application/json" },
})
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
.then(() => this.getBillProjLastId());
}
The API route I'm trying to reach is this:
app.put("/billingcalculator/create", function (req, res) {
console.log("It is getting to the billing route");
const client = req.body.client;
const source = req.body.source;
const projectName = req.body.projectName;
console.log(`client: ${client}`);
console.log(`source: ${source}`);
console.log(`project name: ${projectName}`);
connection.getConnection(function (err, connection) {
connection.query(
`INSERT INTO billcalc_projects (client, source, project_name)
VALUES (?, ?, ?)`,
[client, source, projectName],
function (error, results, fields) {
connection.release();
if (error) throw error;
res.json(results);
console.log(`Billing Project has been created`);
}
);
});
});
Thanks in advance for your help. It must be something simple that I'm just missing. But I haven't been able to figure it out.

Front end JS fetch(POST) request being sent as a GET?

So this fetch request is called on the submit button.
For some reason, in the dev tools, it goes through as a GET. Tested the request in Insomnia, and it ends up returning the site to me (the handlebars site)... and none of my console logs ever show up (on the backend or the front)
Front End
const newPostSubmit= async function(event) {
console.log('didnt make it');
event.preventDefault()
console.log('made it');
const title = document.getElementById('post-title').value;
const content = document.getElementById('content').value;
const response = await fetch(`/api/posts/`, {
method: 'POST',
body: JSON.stringify({
title,
content
}),
headers: {
'Content-Type': 'application/json'
}
});
if (response.ok) {
console.log('Post Success!')
// document.location.replace('/dashboard');
} else {
alert(response.statusText);
}
}
document.getElementById('submit-post').addEventListener('submit', newPostSubmit);
Back End Route To Be Used
router.post('/', checkAuth, (req, res) => {
const body = req.body
console.log(body);
Post.create({ ...body, userId: req.session.userId })
.then(dbPostData => {
console.log(dbPostData);
res.json(dbPostData)
})
.catch(err => {
console.log(err);
res.status(500).json(err);
});
});
The problem was with my HTML. The id of 'submit-post' was placed on the button, but needed to be on the form itself (the button was within the element) which is why the function would never run

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

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

Calling Api post method on button click in React

I have an event like below:
handleDownload(e) {
e.preventDefault();
alert('Hi');
let communityName = this.state['selectedCommunity'];
let files = this.state[files];
fetch(clientConfiguration['filesApi.local'], {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ communityName: communityName, body: files })
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err))
};
I have a button as below:
renderDownloadButton() {
if (this.state.files && this.state.files.filter(i => i.checked).length) {
return (
<button id="download" styles="display: none;" onClick={this.handleDownload} >
Download
</button>
);
}
};
It fires but it is giving following error, any help please - thank you. At
let communityName = this.state['selectedCommunity'];
its giving me the error;
Can not read property state undefined
Any help please?
My guess is that you need to bind your handler, but it's really hard to tell without whole component code.
handleDownload = (e) => {
e.preventDefault();
alert('Hi');
let communityName = this.state['selectedCommunity'];
let files = this.state[files];
fetch(clientConfiguration['filesApi.local'], {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ communityName: communityName, body: files })
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err))
}
For the api post not fetching the error can be one possible case of CORS error that browser do not allow you to access other network(private and secured IP address) so you need to actually allow the proxy setting as I can see your post data don't have any proxy enabled. Here is the code I am attaching
This is the pseudo code please make changes accordingly in your fetch method:
var targetUrl ='/downloadableReport'
const res= fetch(targetUrl,{
method: 'POST',
headers: {
'Content-Type': "application/json; charset=utf-8",
},
body: JSON.stringify({
"requestData":{
"userName":"XXX",
"password":"XXXX",
"clientId":"XXXX",
"txnType":"XXXX"
}
})
})
.then(response => response.json())
.catch(error =>{
console.log(error)
})
Also, you need to add setupProxy.js file (mind the name of the file should be this only) and add this code (with preferred changes)
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(
proxy("/downloadableReport",{
target:"http://192.168.1.220:8080/report/abc" ,
changeOrigin:true
})
)
};

Categories

Resources