Express not rendering page after a POST request - javascript

My goal is to have an onclick function send a post request to delete an HTML li off the page. The post request uses a mongoose function to delete the data then I want the page to be reloaded so the user sees the new page without the item they deleted. The deletion works fine however I have to refresh the page to see it be deleted. There isn't any error messages.
garage.jade
doctype html
html(lang='en')
head
script
include ../Scripts/garage_scripts.js
body
h1 Welcome to The Garage
h2= title
ul
- for (let i=0; i<list_o_cars.length; i++)
li(onclick='delete_car(this)', id="cars")= list_o_cars[i]
garage_scripts.js
function delete_car(target) {
const data = {
car: target.innerHTML,
};
const url = "http://localhost:3000/car_module/delete";
let request_param = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(data),
};
fetch(url, request_param);
}
controller.js
exports.delete = function (req, res, next) {
res.send("hi")
[enter image description here][1]//this would be a render but I am just testing to see if it will reload or redirect to a new page
this is the image of the request preview

Since fetch returns a promise, you can resolve it with .then() and reload the page.
fetch(url, request_param).then(function(res) {
window.location.reload();
}).catch(function(error) {
console.log(error);
});

Maybe just add window.location.reload(); after fetch().
Someone did a much better job of explaining this than I am, HERE

Related

EJS view will not render when triggered via fetch API

in my client javascript I am using the following function, which is triggered by an onclick event
function submitForm(event) {
const data = { name, image_url };
console.log(data);
fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
}
The function above sends a post request to the expressJS backend of the app which triggers another function that is supposed to render one of two EJS views. here is the expressJS function
router.post('/', function (req, res) {
console.log('hitting router post');
var { name, imageURL } = req.body;
console.log(name, imageURL);
if (nicknameIsAvailable(name)) {
let user = {
nickname: name,
id: '',
image: imageURL,
};
console.log("new user connecting")
res.cookie('nickname', name, { signed: false });
res.render('chat', { nickname: name });
} else {
console.log('rejecting user ' + name + ' is already taken');
res.render('index', { message: userTakenErrorMessage });
}
});
problem is that res.render does not actually render the EJS view. I think what is happening is that it's sending back the HTML markup of the view to the client side javascript. The desired behavior would be for it to render the "chat" or "index" views with the given arguments. How can I achieve that?
If this approach does not work then what approach could I use to add some data to the body of a request without using a form and then having that request trigger rendering a view?
This is an ajax request, you will receive rendered HTML in the resolved promise of fetch function. To display the response content use:
fetch(...).then(res => res.text()).then(htmlStr => {
document.open();
document.write(htmlStr);
document.close();
})

How do I detect that app_offline.html is being served?

My website serves an app_offline.htm file when it is down for maintenance. I want to force clients to reload when they detect that this page is being served. This way my users see an app_offline page immediately instead of having to refresh.
I figured out how to send a request to the server in JavaScript...
const opts = { method: 'GET', headers: {} };
fetch('/', opts)
.then(function (response) {
console.log('response from server:', response);
});
Output:
I don't know how to check the response to see if it is my app_offline page. I tried this:
if (response.statusCode === 503)
window.location.href = window.location.href; // Reload the page
The problem with this approach is that I'm not sure if 503 error necessarily means that my app_offline page is being served. If the website is inaccessible for any other reason, then I want the user stay on the page.
If I could set the statusText on the response, then I could check that. I couldn't figure out how to do it on a static page.
You just need to listen for an error after any fetch request you do.
fetch('/', opts)
.then(function (response) {
console.log('response from server:', response);
}).catch(err => {
reloadPage();
});
let reloadPage= () => {
window.location.href = window.location.href; // Reload the page
}

POST and GET API Request using fetch, cannot get the data

i'm trying to use this website: https://rel.ink/,
to implement a link-shortener in my webapp,
i can successfully POST a request, but what i GET back is the same object, not a shortened version.
I know it's basic stuff but i can't wrap my head around it.
The website states that i need to send more information with my GET request, but the GET requests should not contain a body yes?
Here's my code:
async function fetchNewLink() {
let newLinkJson = await postLink(input.value)
let newLink = await getShortLink(newLinkJson)
console.log(newLink)
}
function postLink(input) {
return fetch('https://rel.ink/api/links/', {
method: 'POST',
body: JSON.stringify({
url: input
}),
headers: {
"Content-type": "application/json"
}
})
.then(response => response.json())
.then(json => json)
}
function getShortLink(response) {
return fetch('https://rel.ink/api/links/' + response.hashid)
.then(result => result.json())
.then(newLink => newLink)
}
Many thanks
If what you're trying to get is the shortened version of the link, the API does not return exactly that when you make a request. However, all you need is the hashid it returns. The shortened link is the main website's url(https://rel.ink) concatenated with the hashid.
So if the API returns nJzb3n as the hashid when you make a POST request, the shortened link would be https://rel.ink/nJzb3n
I hope that helps.

How to redirect user to a page after receiving the response from a fetch POST request?

I am writing code for a web application that send a POST request to node.js server using fetch() api of javascript. On successful request server responds with a redirection, this redirection url is received in the fetch() api response body. After this what should I do to redirect user to this URL from fetch function.
fetch("/events/registration", {
method: "POST",
redirect:"follow",
headers: {
"Accept": "application/json , text/plain ,*/*",
"Content-type": "application/json"
},
body: JSON.stringify({
name,
email,
})
})
.then((res)=>res.json())
.then((data)=>{console.log(data);if(data.err)alert(data.err);Response.redirect()});
In response that i receive in fetch api I am getting redirect:true , url: "LinkOfRedirection/redirect", now what should i do to redirect user from here to the LinkOfRedirection/redirect.
// Sets the new location of the current window.
window.location = res.url;
// Sets the new href (URL) for the current window.
window.location.href = res.url;
// Assigns a new URL to the current window.
window.location.assign(res.url);
// Replaces the location of the current window with the new one.
window.location.replace(res.url);
// Sets the location of the current window itself.
self.location = res.url;
// Sets the location of the topmost window of the current window.
top.location = res.url;
Or you can use
res.redirect(301, res.url);
A simple solution to this would be something like this:
fetch('/api/login/' , {
method : 'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken' : csrf,
},
body : JSON.stringify(data)
}).then(result => result.json())
.then(response => {
if(response.status == 200){
window.location.href = '/'
}
else{
alert(response.message)
}
})

Add parameters to post request using js on client side

I'm developing a "TODO" app using node.js and mongodb.
I'm trying to post a new task from the client but I didn't success to pass parameters to the server and from there to the database.
Client code:
<script>
function addData(item, url) {
var text = document.getElementById("myTask").value;
return fetch('/todos',{
method: 'post',
body: text
}).then(response => response.json())
.then(data => console.log(data));
}
</script>
Server code:
app.post('/todos',(req,res) =>{
console.log("\n\n req.body is: \n\n",req.body);
var todo = new Todo({
text: req.body.text});
todo.save().then((doc) =>{
res.send(doc);
console.log(JSON.stringify(doc,undefined,2));
},(err) =>{
res.status(400).send(err); //400 = unable to connect
console.log("Unable to save todo.\n\n\n" , err);
});
});
And the problem is that the client doesn't send the body to the server,
and the body is null on the server side:
See the logs here
(as you can see: req.body = {})
In the js code, I tried to pass the body parameter but I guess I did something wrong so I want to know the best way to pass parameters back to the server (not only the body but text, time and etc)
Thank in advance,
Sagiv
I think that you are missing something. Try to use name of param
body: JSON.stringify({data: text})
OR
read here Fetch: POST json data
I used this code:
(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await rawResponse.json();
console.log(content);
})();
and now I succeeded to pass data to the request.
Thanks everybody

Categories

Resources