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
Related
I have an asp.net core MVC server set up, I am trying to enable some better error handling. However when I deploy my changes to production environment I have a discrepancy in my server responses when dealing with 4xx errors.
When running on my local host i am able to send custom response data back to the client and read this data no problem, however when i attempt the same thing after live deployment I cannot read the responses the same way And I do not understand why.
Controller
[HttpPost]
public JsonResult SaveRecord([FromBody]NewsLanguage newLanguage)
{
//NewsLanguage newLanguage = new NewsLanguage()
try
{
_context.NewsLanguages.Add(newLanguage);
_context.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Response.StatusCode = 409;
string errMsg = ex.Message;
if (ex.InnerException != null)
errMsg = ex.InnerException.Message;
return Json(new { status = "Error", message = errMsg });
}
Response.StatusCode = 200;
return Json(new { status = "success",
message = "New News Language Saved Successfully!" });
}
fetch request
try {
const response = await submitForm("/saverecord", newsLanguage, "POST");
console.log(response);
if (response.ok)
handleResponse(response, newsLanguage);
else {
const err = await response.json();
throw new Error(err.message || err.statusText)
}
} catch (err) {
console.log(err);
handleErrorResponse(err, newsLanguage);
}
function submitForm(route, newsLanguage, method) {
const requestOptions =
{
method: method,
headers:
{
'Content-Type': 'application/json'
},
body: JSON.stringify(newsLanguage)
};
return fetch(parurl + route, requestOptions);
}
async function handleResponse(response, newsLanguage, method) {
const data = await response.json();
console.log(response, data)
if (data.status === "success") {
//have to close modal this way since using
//jquery hide leave backdrop open and causes
//issue with subsequent modal openings
document.getElementById("ModalFormClose").click();
toastr.success(data.message, "PERLEWEB DATABASE INTERFACE");
if (method != "DELETE") {
let table = $('#example').DataTable();
table.row.add({ "id": newsLanguage.Id,
"languageName": newsLanguage.LanguageName }).draw();
} else {
var table = $('#example').DataTable();
table.row($(this).parents('tr')).remove().draw();
}
} else {
toastr.error(response.responseJSON.message, "ERROR!")
}
}
function handleErrorResponse(errorMsg) {
toastr.error(errorMsg, "ERROR!")
}
So it seems the custom error message i send when sending the 409 response is not there in the client in production, however, the success message is i can read it as expected and display the message, however when trying to read the response.json() after checking if response is ok (and when it is not) the response message is "SyntaxError: Unexpected token T in JSON at position 0" which based on some other research suggest it is undefined.
So my main questions are,
1- where is my error message for failures?
2- Is there a way i can get it display the error message, or can i only send http response code for error?
3- why does it work for success response but not error?
4- why is there this difference btwn localhost vs production is this a server configuration issue?
Thanks
After Much investigation, it turns out the source of the issue was in the web.configurations.
Since the project is being inside of another web app i had to add a section to my web.config which specifies a different custom error handling method than the rest of the site. specifically i added the below
<location path="webdb">
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
<clear/>
</httpErrors>
</system.webServer>
</location>
And Now i am able to parse the Error response custom text in my JS and display the message from the server
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
}
When I request data on client(vue.js) with axios,
I got a error code in server side, 'GET/ 304 --'
But I don't know why this happened
and how to approach this problem or how to fix that.
If I delete codes about 'axios' on client side,
That error doesn't show up.
Please can someone help me.
the code below:
Client side
created() {
axios
.get("http://localhost:4000/")
.then(
result => (
(this.greeting = result.data.greeting),
(this.greeting2 = result.data.greeting2)
)
);
}
Server side
export const getHome = async (req, res) => {
let user;
if (req.headers.authorization !== undefined) {
try {
user = auth.verify(req.headers.authorization);
user = await models.User.findOne({
where: { id: user.id }
});
} catch (err) {
console.log(err);
}
} else {
user = null;
}
const name = user ? user.name : 'Please LOGIN';
res.json({ greeting: `Welcome to Chat N Chill`, greeting2: name });
};
auth.verify code on server side
verify(token) {
return jwt.verify(token.replace(/^Bearer\s/, ''), SECRET_KEY);
}
Express will automatically set the status code to 304 for requests that are fresh:
https://github.com/expressjs/express/blob/e1b45ebd050b6f06aa38cda5aaf0c21708b0c71e/lib/response.js#L206
The property fresh is defined here:
https://github.com/expressjs/express/blob/e1b45ebd050b6f06aa38cda5aaf0c21708b0c71e/lib/request.js#L467
It is documented here:
https://expressjs.com/en/4x/api.html#req.fresh
It should be nothing to worry about, it just means that the content of the response hasn't changed relative to what the browser already has in its cache.
I have setup axios with interceptors this way
const axiosConfig = {
baseURL: 'http://127.0.0.1:8000/api',
timeout: 30000
};
axios.interceptors.response.use((response) => { // intercept the global error
console.log("response is", response);
return response
}, (error) => {
console.log("errors are", error);
if (error.response.status === 401) {
// if the error is 401 and hasent already been retried
alert("You will need to login to access this");
window.location.href = '/auth/login'
return
}
if (error.response.status === 404) {
window.location.href = '/'
return
}
});
Vue.prototype.$axios = axios.create(axiosConfig)
But the above interceptors dont work.Where am i going wrong? The console.log() messages fail to work.
I'm sending you minimal working example of how to intercept ajax before request is started. I have a button on the page, and then I'm binding it to pull some data, but before that I have console.log'ed the interceptor message => you can replace that with your logic.
Hope that can help you get started..
// let's intercept axios ajax call BEFORE it starts
var INTER = axios.interceptors.request.use(
function(config){ console.log('intercepted!'); return config;},
function(error){return Promise.reject(error);}
);
// function to pull remote data
function pullData(){
var url = 'https://jsonplaceholder.typicode.com/posts';
axios.get( url )
.then(function (response) {
console.log(response.status);
})
.catch(function (error) { console.log(error); });
}
// reff the button on the page
var b = document.getElementById('b');
// bind to click event
b.addEventListener('click', pullData, false);
<script src="https://unpkg.com/vue#2.5.8/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios#0.17.1/dist/axios.min.js"></script>
<button id="b">Click to pull http req resource</button>
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];
}