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

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
}

Related

Express not rendering page after a POST request

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

Get only HTML in single fetch request in service worker

I'm using Cloudflare service workers and I want on every request to:
request only the HTML (therefore count as only 1 request)
search the response for a string
Purge that page's cache if the message exists
I've solved points #2 and #3. Can't figure out if #1 is feasible or possible at all.
I need it as only one request because there is a limit per day on the number of free requests. Otherwise I have about 50-60 requests per page.
My current attempt for #1, which doesn't work right:
async function handleRequest(request) {
const init = {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
};
const response = await fetch(request);
await fetch(request.url, init).then(function(response) {
response.text().then(function(text) {
console.log(text);
})
}).catch(function(err) {
// There was an error
console.warn('Something went wrong.', err);
});
return response;
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest(event.request))
});
You can't request "only the html", the worker will act on any request that matches the route that it is deployed at. If you only care about the html, you will need to set up your worker path to filter to only the endpoints that you want to run the worker on.
Alternatively you can use the worker on every request and only do your logic if the response Content-Type is one that you care about. This would be something along these lines:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
})
async function handleRequest(request) {
let response = await fetch(request);
let type = response.headers.get("Content-Type") || "";
if (type.startsWith("text/")) {
//this is where your custom logic goes
}
return response;
}

How to clear the cached statusCode in net request electronjs?

In my app, I use net.request(url). I need to get the statusCode to display the right page e.g if the statusCode is 404, I want redirect to not-found.html̀.
Unfortunately, there is a problem with a cache somewhere :
Firstly, when the statusCode is 404, the app redirects to the 404 url template. It's ok.
Then, when I repair the page, I have a statusCode 200, the app redirects to the right page url. It's ok.
But when I broke my page again (it should be 404 not found), I get a statusCode 200 !
How to clear the app or this request?
my code:
const request = net.request(url);
request.on("response", (response) => {
// console.log(`STATUS: ${response.statusCode}`)
// console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on("data", (chunk) => {});
response.on("end", () => {
if (response.statusCode === 200) {
win1.loadURL(url, { extraHeaders: "pragma: no-cache\n" });
win1.show();
} else {
let url = `file://${__dirname}/not-found.html`;
win1.loadURL(url, { extraHeaders: "pragma: no-cache\n" });
win1.show();
}
});
});
request.end();
You can disable disk cache.
When you start the application, add the --disable-http-cache parameter as explained here :
electron . --disable-http-cache

Getting 401 error when using redmine API for a POST request even though I have included the api key

I am trying to make a post request to create a new wiki page using the redmine-api. I am using JavaScript and Axios. However I a getting a 401 error(UnAuthorize).
My goal is to be able to send a word document to my redmine and create a wiki page.
I am using the Api key provided and I did enable the rest api feature in my redmine setting
I have included the api key in the header however it is not working.
var wordDocument = "./Redmine.docx"
axios.post('<website url>/uploads.json', {
headers: {
'Content-Type': 'application/octet-stream',
'Cache-Control': 'no-store',
'key': '<api-key>'
},
data:wordDocument
})
.then(function (response) {
console.log("succeeed---> ");
console.log (response)
})
.catch(function (error) {
console.log("failed-----> ");
console.log(error.response.headers)
console.log(error.message)
console.log("failed-----> ");
})
I am getting a status: '401 Unauthorized',
Try using the other authentication methods mentioned in the docs:
x passed in as a "key" parameter
- passed in as a username with a random password via HTTP Basic authentication
- passed in as a "X-Redmine-API-Key" HTTP header (added in Redmine 1.1.0)
https://www.redmine.org/projects/redmine/wiki/Rest_api#Authentication
Also ensure that you're using the correct API key.
You can find your API key on your account page ( /my/account ) when logged in, on the right-hand pane of the default layout.
Alright I got it working.
I did "axios({})" instead of "axios.post". I do not know what the different is? I thought it was the same.
Here is my code for anyone who run into this.\
var wordDocument = "./Redmine.docx"
axios({
method: 'post',
url: '<redmind_url>/uploads.json',
headers: { 'Content-Type': 'application/octet-stream'},
params: { 'key': '<api key>'},
data: wordDocument
})
.then(function (response) {
console.log("succeeed---> ");
console.log(response.data)
})
.catch(function (error) {
console.log("failed-----> ");
console.log(error.response.statusText, "-->", error.response.status);
console.log(error.response.headers)
console.log(error.message)
console.log("failed-----> ");
})

Redirect client while performing a function with Express

Right now, I have an Express route that is posted to by a form, below is a truncated example. The initial form is inside an iframe, so after I receive a response from http://example.com/endpoint, I send a response back to the iframe with a link going to a "signing" page, targeting the parent frame.
Unfortunately, the response from http://example.com/endpoint can take pretty long, which causes the iframe to timeout and never receive a response. What I'd like to do is send some type of response back to the iframe immediately and redirect the page to some sort of "loading page" – this would be shown while the router waits for a response from http://example.com/endpoint.
I'm using Express to serve the page that contains the iframe to the user right now – all the views are controlled on the server side.
I'm wondering if there's any resources somebody could point me towards, or something to nudge me in the right direction.
router.post('/api/orders', function(req, res) {
var order = {
'model': req.body.model,
'options': optionsArray
}
request.post({
url: 'http://example.com/endpoint,
body: order,
json: true
}, function(err, response, body) {
if (!error && response.statusCode === 200) {
if (!body.isCustom) {
hellosign.embedded.getSignUrl(body.signatureId)
.then(function(response) {
var signatureUrl = response.embedded.sign_url;
var resSignatureUrl = encodeURIComponent(signatureUrl);
res.send('Click to sign');
})
.catch(function(err) {
console.log(err);
})
} else {
res.send('You selected custom options.');
}
}
if (error || response.statusCode === 403) {
res.json({
message: 'something went wrong with your order',
errorCode: response.statusCode,
errorMessage: body.message
});
}
});
});
I would put the hellosign/whatever long running API call in its own module. Test that separately to make sure its working.
Then your iframe or whatever (do you really need an iframe?) sends the request which is just a 'start order' request which gets an order id from the hellosign module. And then use a setInterval or something to check a new endpoint which is an 'orderstatus' endpoint.
Your orderstatus endpoint accesses your new hellosign module to check the status of the order.
So it could be something like:
post('/start', function(req,res) {
var id = hellosign.startorder(req.body.model);
res.send(id);
});
get('/status', function(req,res) {
res.send(hellosign.checkstatus(req.body.id));
}
// hellosign.js
var status = {};
exports.startorder = function(model) {
var id = uuid.v4(); // some unique id;
status[id] = 'started';
request.post(api, /* ... */ ).then(function(signurl) { status[id] = signurl });
return id;
}
exports.checkstatus = function(id) {
return status[id];
}

Categories

Resources