Time for me to ask some help as I simply do not understand the issue, spent a good 6 hours on this, going nowhere :-(
I have an Axios GET request which may have the last parameter empty.
axios.get(this.fetchAllUsersRoute + '/' + this.status + '/' + this.pagination + '/' + this.search);
My laravel route:
Route::get('/fetch-users/{status}/{pagination}/{search?}', 'MyController#fetchUsers')->name('fetch-users');
When the this.search is empty I am getting this:
Request URL: https://mywebsite.dev/fetch-users/0/1/
Request Method: GET
Status Code: 301 Moved Permanently (from disk cache)
It redirects to here on each request:
https://mywebsite.dev/fetch-users/0/1
The last / slash seems to be causing a redirection when this value is left empty.
As soon as I remove it, the problem stops...no redirection.
Any idea how I can make the last slash disappear if the last value is empty?
Thank you.
Your request is incompatible with the route. You can try to create request link like below.
var fetchAllUsersRoute = "https://mywebsite.dev"
var status = 'status'
var pagination = 'pagination'
var search
var url = fetchAllUsersRoute + '/' + status + '/' + pagination + (search != null ? ('/' + search) : '')
console.log(url)
// "https://mywebsite.dev/status/pagination"
search = 'search'
url = fetchAllUsersRoute + '/' + status + '/' + pagination + (search != null ? ('/' + search) : '')
console.log(url)
// "https://mywebsite.dev/status/pagination/search"
Related
I want to update a varchar field (String) using and End-Point Api (Express NodeJS) but I have problem went I pass invalid inputs like question mark.
Express End-Point:
router.get("/updateField/:table/:field/:value/:num/:postid/", function(req, res) {
connection.query(
'UPDATE '+ req.params.table +' SET ' + req.params.field +' = '+JSON.stringify(req.params.value) +' where language ='+ req.params.num +' and post_id ='+req.params.postid
This code work fine:
http://localhost:3001/api/updateField/posts/TITLE/When/1/1
But this NOT WORK:
http://localhost:3001/api/updateField/posts/TITLE/When?/1/1
I send the request from react like this:
fetch(
"http://localhost:3001/api/updateField/" +
table +
"/" +
field +
"/" +
value +
"/" +
lenguage +
"/" +
post_id
);
Use javascript function encodeURIComponent() to escape special characters in URL parameters.
For example try this on your browser console and you'll get an idea:
console.log(
"http://localhost:3001/api/updateField/" +
table +
"/" +
field +
"/" +
encodeURIComponent(value) +
"/" +
lenguage +
"/" +
post_id
);
console.log(encodeURIComponent("When?"));
You will see that "When?" is replaced with "When%3F" in URL.
In Node.Js, you'll receive parameter value as string "When?".
To know more about encodeURIComponent(), refer to this
I'm facing a little issue with a javascript script. I'm trying to make my website multi languages. All is set in database, and my select works on pages where the URLs don't have variables. Here is my script:
<script type="text/javascript">
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
window.location.href = window.location.pathname + '?lang=' + thelang;
}
</script>
In the homepage case, it works, and change http://localhost/ by http://localhost/?lang=en
But when I have an URL with a variable already set, it replaces it. From http://localhost/modules/product/product.php?id=1 I have http://localhost/modules/product/product.php?lang=en and the result I'd like is:
http://localhost/modules/product/product.php?id=1&lang=en
How to fix the script to make it works in both cases, or add the varibale, or glue it with an existing one?
Try checking to see if querystring params already exist in the URL.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
if (window.location.href.indexOf('?') >= 0) {
// There are already querystring params in the URL. Append my new param.
window.location.href = window.location.href + '&lang=' + thelang;
} else {
// There are not querystring params in the URL. Create my new param.
window.location.href = window.location.href + '?lang=' + thelang;
}
}
Update: Account for Subsequent Lang Changes
This assumes that the lang value will always be two characters.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
var newUrl = window.location.href;
var langIndex = newUrl.indexOf('lang=');
if (langIndex >= 0) {
// Lang is already in the querystring params. Remove it.
newUrl = newUrl.substr(0, langIndex) + newUrl.substring(langIndex + 8); // 8 is length of lang key/value pair + 1.
}
// Remove the final '?' or '&' character if there are no params remaining.
newUrl = newUrl.endsWith('?') || newUrl.endsWith('&') ? newUrl.substr(0, newUrl.length - 1) : newUrl;
newUrl = newUrl.indexOf('?') >= 0
? newUrl + '&lang=' + thelang // There are already querystring params in the URL. Append my new param.
: newUrl + '?lang=' + thelang; // There are not querystring params in the URL. Create my new param.
window.location.href = newUrl;
}
If I understand you correctly you want to add ?lang=en at the end. Unless there is already an id=1(or similar) there.
So you could just add an if statement, looking if there is .php writen at the end.
Not a very pretty solution but you are alreaady adding strings together so it doesn't matter
You can use the "search" element of window.location. See here for compatibility. You can then, concat the result with your desired parameter. BUT, you can do something way more complex (and secure) and check if there's already a parameter with that ID using a for + URLSearchParams.
const params = new URLSearchParams(window.location.search);
const paramsObj = Array.from(params.keys()).reduce(
(acc, val) => ({ ...acc, [val]: params.get(val) }), {}
);
This should fix it:
var currentUrl = window.location.origin + window.location.pathname;
var newUrl = currentUrl + (currentUrl.includes('?') ? ('&lang=' + thelang) : ('?lang=' + thelang));
window.location.href = newUrl;
return (url = url.substr(1 + url.lastIndexOf("/")).split('?')[0]).split('&')[0].substr(url.lastIndexOf("."));
I have above code which return [.exe] or [.pdf]
Where I expect only [EXE] or [PDF]
What changes do I require in the above code?
Just Add 1 to last Index
return (url = url.substr(1 + url.lastIndexOf("/")).split('?')[0]).split('&')[0].substr(url.lastIndexOf(".") + 1);
I have been digging in some javascript api's lately and I found the following line:
get_url_info: function($db_link) {
var ldst_href;
if ($db_link.data('ldst-href')) {
ldst_href = $db_link.data('ldst-href');
}
else {
ldst_href = $db_link.attr('href');
}
var matchs = ldst_href.match(/^http:\/\/([^\.]+)\..*playguide\/db\/(.*?)\/?(#.+)?$/);
var subdomain = matchs[1];
var path = matchs[2];
if (!eorzeadb.dynamic_tooltip && eorzeadb.versions.data) {
url = eorzeadb.cdn_prefix + 'pc/tooltip/' + eorzeadb.versions.data +
'/' + subdomain + '/' + path + '.js';
}
else {
url = ldst_href + '/jsonp/';
}
return {
'url': url,
'data_key': subdomain + '/' + path
};
},
This result is supposed the return an array which I assume is contained in the link. I'm having a hard time decrypting the link tho.
Does anybody have any experience with these kinds of links or a way that I could start out?
http://regexr.com/
Here you can understand all the parts of the regex. Basically, is looking for a pattern like this:
http://(blablah).playguide/db/(OPTIONAL)(optional/)#(probably some id)
The result will be an array with the original link, followed by the domain, the first optional argument, and the hashtag, something like this
["http://(blablah).playguide/db/(OPTIONAL)(optional/)#(probably some id)", "(blablah)", "(OPTIONAL)(optional/)", "#(probably some id)"]
It will then use that information to build a different link
I'm getting a response back with body "unable to validate oauth signature and token" when trying to get the request token.
Here's the code I'm using to set up all the request parameters. I noted some places of interest that I think could possibly be the problem with a bunch of asterisks.
var appId = "myId"
, appSecret = "mySecret"
, redirectUrl = "http://localhost:8077/twitterLogin";
var d = new Date();
, time = Math.floor(d.getTime() / 1000); //seconds since epoch
var oauth_nonce = Math.random() * 1000000; //************could be the issue, maybe?
, oauth_callback = encodeURIComponent('http://localhost:8077/twitterLogin');
//****************more likely the issue
var paramString = encodeURIComponent('oauth_consumer_key=**MY_APP_ID**&oauth_callback='+ oauth_callback
+ '&oauth_nonce=' + oauth_nonce
+ '&oauth_signature_method=HMAC-SHA1&oauth_timestamp=' + time
+ '&=oauth_version=1.0');
var baseString = "POST&" + encodeURIComponent("https://api.twitter.com/oauth/request_token") + '&' + paramString;
var signingKey = encodeURIComponent(appSecret) + '&' + encodeURIComponent(appSecret);
, signature = crypto.createHmac('sha1', signingKey).update(baseString).digest('hex');
And here's the code for the request itself:
var requestBody = "oauth_callback="+ oauth_callback
+ "&appId=" + appId
+ "&oauth_nonce=" + oauth_nonce
+ "&oauth_signature=" + signature
+ "&oauth_signature_method=HMAC-SHA1"
+ "&oauth_timestamp=" + time
+ "&oauth_version=1.0";
//*******also could be the issue. maybe missing headers or something?
request.post({url: 'https://api.twitter.com/oauth/request_token', body: requestBody});
I'm just wondering what I'm missing with the signature or the token..
Firstly your parameters have to be sorted lexigraphically
(alphabetically) before they are encoded, you need to switch the
positions of oauth_callback and oauth_consumer_key.
Secondly, for an
unauthorized request token, you calculate the signing key using your
consumer secret appended with the '&' character. You have appended
the secret a second time after the ampersand.
Thirdly in your request
body you should use oauth_consumer instead of appId as the name of
your parameter.
Try those fixes and see if it works.