GET request firing 2 or 3 trying to load 1 page - express

In my router
Router.get('/login', IndexController.login);
In my controller
exports.login = (req,res,next)=>{
console.log('login get');
res.render('main/login',{pageTitle: 'Login'});
};
The console logs login get twice, meaning that this is called twice. If I remove the render call then it is logged only once. I have been trying to debug for several days now but still cant seem to figure this one out. When using a curl request from another terminal the log is seen only once as well, but using chrome/firefox/IE yields the double or sometimes triple log call. I don't see this behaviour with POST calls however.
-EJS
-EXPRESS
-Node
UPDATE
In chrome dev tools, after inspecting the network tab, I only see 1 GET request being made for the page. It seems that using res.send() only fires the log once however using res.render(....) goes twice or three times.

Related

Express sendFile() and page refresh

I have a simple express server with paths /login which returns Login.html and /play which returns game.html using res.sendFile().
When I go to the end points directly on Crome, I can display the mentioned pages accordingly, however, I want to go to /play from a button in login.html. I created a function using fetch api and added that to the button as a click event listener.
The problem is that, everything works fine, except the browser is stuck in login.html. It does not refresh to game.html.
The request the button triggers receives a 304 code.
The desired functionality can be achieved setting windows.location.href to ‘…/play’, but I don’t understand why it doesn’t work the way mentioned above.
It works fine when those endpoints are hit separately but why not when /play is triggered from a button in login.html.
I can later add the code.

node express multer fast-csv pug file upload

I trying to upload a file using pug, multer and express.
The pug form looks like this
form(method='POST' enctype="multipart/form-data")
div.form-group
input#uploaddata.form-control(type='file', name='uploaddata' )
br
button.btn.btn-primary(type='submit' name='uploaddata') Upload
The server code looks like this (taken out of context)
.post('/uploaddata', function(req, res, next) {
upload.single('uploaddata',function(err) {
if(err){
throw err;
} else {
res.json({success : "File upload sucessfully.", status : 200});
}
});
})
My issue is that while the file uploads successfully, the success message is not shown on the same page, ie: a new page is loaded showing
{success : "File upload sucessfully.", status : 200}
As an example for other elements (link clicks) the message is displayed via such javascript:
$("#importdata").on('click', function(){
$.get( "/import", function( data ) {
$("#message").show().html(data['success']);
});
});
I tried doing a pure javascript in order to workaround the default form behaviour but no luck.
Your issue has to do with mixing form submissions and AJAX concepts. To be specific, you are submitting a form then returning a value appropriate to an AJAX API. You need to choose one or the other for this to work properly.
If you choose to submit this as a form you can't use res.json, you need to switch to res.render or res.redirect instead to render the page again. You are seeing exactly what you are telling node/express to do with res.json - JSON output. Rendering or redirecting is what you want to do here.
Here is the MDN primer on forms and also a tutorial specific to express.js.
Alternatively, if you choose to handle this with an AJAX API, you need to use jquery, fetch, axios, or similar in the browser to send the request and handle the response. This won't cause the page to reload, but you do need to handle the response somehow and modify the page, otherwise the user will just sit there wondering what has happened.
MDN has a great primer on AJAX that will help you get started there. If you are going down this path also make sure you read up on restful API design.
Neither one is inherently a better strategy, both methods are used in large-scale production applications. However, you do need to choose one or the other and not mix them as you have above.

getJson method returns an error using woocommerce JSON API plugin

I'm using woocommerce JSON API to retrieve the data of some products like price, SKU, etc...
The thing is that I get an error using this API. I've installed the plugin succesfully and activated it in the WordPress Dashboard.
I've tried the example given in GitHub exactly as the author says.
Here's my javascript code:
$(document).on('pageinit','#restau' ,function(){
var url = 'http://danielvivancos.com/edu/wordpress/shop/?callback=?';
params = { action: 'woocommerce_json_api', proc:"get_products"};
params.arguments = {token: 1234, per_page: 2, page: 1}
jQuery.getJSON(url,params).done(function (data) {
alert("success");
console.log(data);
console.log(url);
}).error(function(jqXHR, textStatus, errorThrown){
alert(jqXHR.responseText);
});
});
At first it didn't do anything, and I didn't understand what was happening but then I added the .error() function and it threw me an error...
Here http://danielvivancos.com/edu/directebre_app_jquerymobile/ you will find the three alerts displayed when you click on any of the three products.
Hope someone can help me or give me some ideas to solve it.
Thank you all!
The API Almost always returns some kind of error string and error code. The one time when it wouldn't would be if there was a PHP error (Even then it tries to catch the error and return something).
One thing you may need to do is to visit the users settings page, setup your permissions, and then save the settings for that API User. Whenever a new method is added to the API you will have to visit this page and resave it.
Another thing to do is to try and run php tests/get_products.php and see what happens. Most of the API functions have a tests file that you can run from the command line to test the API.
Also, while I am very happy you are using it :) it is still unfinished and in the early stages of development.
It looks like your example is working though?
Could you post a bit more about what error you are getting?
When I click on one of the items, it takes me to a page where a popup shows up with a bunch of HTML, this normally means that your API page is not setup properly (if it is making an api request). You will need to setup the API page ( Just create a wordpress page, or use an existing one) Then in the WooCom menu select JSON Api, and set the API page from the dropdown list. Remember to save.

YII getFlashes() not deleting?

Before jumping in with an answer, please make sure you understand my scenario.
I have ajax calls that CREATE flashes.
I have other ajax calls that FETCH the flashes as JSON.
What is currently happening: I click a button which creates the flash. After which I run a ajax call that executes:
public function actionGetAllFlashesAsJSON() {
$flashMessages = Yii::app()->user->getFlashes(true);
$returnResult = array();
foreach ($flashMessages as $key => $value) {
$newItem = array();
$newItem['message'] = $value;
$newItem['kind'] = $key;
$returnResult[]= $newItem;
}
print json_encode($returnResult);
die();
}
My problem is, when I execute this function twice in a row, it still keeps returning the flashes. However, if I refresh the site, it shows the error, and then if I press refresh again, it's gone. My theory is that page refresh is causing some other kind of deletion of messages... but what? And how can I force the deletion of these messages after I receive the message in the above code?
More background info: I am using the flashes as ERROR messages, but i want them to appear at the top of my site AS THEY ARE CREATED. Flashes might get created via Ajax, so I have javascript running to check for new messages, and display them, but my problem is it shows the messages several times, because they are not getting deleted after calling getFlashes?
The flash messages are controlled by SESSION variables, which Yii destroys when the page is loaded (probably somewhere quite deep in the framework). You will have to manually destroy all the previous flash messages at the start of the ajax request
You can use: getFlashes() to get all the existing flash messages
For the other flash message methods have a look at the CWebUser docs here

How can I block based on URL (from address bar) in a safari extension

I'm trying to write an extension that will block access to (configurable) list of URLs if they are accessed more than N times per hour. From what I understand, I need to have a start script pass a "should I load this" message to a global HTML page (who can access the settings object to get the list of URLs), who will give a thumbs up/thumbs down message back to the start script to deny/allow loading.
That works out fine for me, but when I use the usual beforeLoad/canLoad handlers, I get messages for all the sub-items that need to be loaded (images/etc..), which screws up the #accesses/hour limit I'm trying to make.
Is there a way to synchronously pass messages back and forth between the two sandboxes so I can tell the global HTML page, "this is the URL in the window bar and the timestamp for when this request came in", so I can limit duplicate requests?
Thanks!
You could use a different message for the function that checks whether to allow the page to load, rather than using the same message as for your beforeLoad handler. For example, in the injected script (which must be a "start" script), put:
safari.self.tab.dispatchMessage('pageIsLoading');
And in the global script:
function handleMessage(event) {
if (event.name == 'pageIsLoading') {
if (event.target.url.indexOf('forbidden.site.com') > -1) {
console.log(event.timeStamp);
event.target.url = 'about:blank';
}
}
}