How to get the id of a post from a URL - javascript

I have a URL that is formatted like this:
http://localhost:3000/post/5dc07270e7179a5293d14e70
The part after /post/ contains an id as you see. I managed to obtain it by doing the following:
const path = this.props.location.pathname;
const postId = path.slice(6, 30);
Is there a better way of obtaining that id in React?

You can split on "/" and slice the result with a negative index (if the id is always the last part of the path).
console.log("http://localhost:3000/post/5dc07270e7179a5293d14e70".split("/").slice(-1)[0]);

Of course, you can preprocess that string and get id out from there, but for the brighter future you should do it another way.
An example of better use is react-router-dom since it lets you define parameters in your URL, and you can easily get that.

You can use withRouter to get the history and location details in the props. From there you can split the url by '/' and the length - 1 will be your id.
Or you can go raw javascript
let url = window.location.href.split('/')
console.log(url[url.length - 1])
If the id is not specified in the url like this
?id=yourid
Then the id must have to be at the end of the url for this to work.

Related

Appending to multiple ids to api call

So I have a call I can make to an api that allows me to toggle whether or not a user has a vip role using this endpoint.
ApiService.patch('/admin/vip?user_id=1&user_id=2')
It can target multiple users at once by appending "user_id=:id" after the question mark with a "&" in between each users id. How could I make a variable of some kind that uses a loop to get the correct user ids and apply "user_id=" before their actual IDs and "&" between each user?
I can handle looping to get the IDs but not sure how to put "user_id=" before each id and "&" after each ID (Only if there is another user_id after the last one)
I'd say the easiest way to achieve this is by having a comma separated value for user_id. In your code you could then do something like query.user_id.split(',') and get an array of all the user IDs you passed in.
Use an array to store ids and then map the array to create the string, using a condition to skip the first. Or use URL Search Params

What is the difference between 'path' and 'query' in a API call

I m trying to implement faceit API in my website.There are two end points from which I can retieve a player's information
1.https://open.faceit.com/data/v4/players?nickname=DeADLY2501&game=CSGO&game_player_id=76561198806878477
This is the first way.Below i will link a image.From faceit documentation(https://developers.faceit.com/docs/tools/data-api)
Here there is a parameter called 'game_player_id' which says it must be a string and 'query'.
Here is the second endpoint
Here in which a parameter is need called 'player_id' which is required needs to be a string and must be a 'path'.
Can some one please tell me what is the difference.Because in the first end point.We need 'nickname','game' and 'game_player_id'.
I just want to retrive a players information just from the id,So that can be made possible by the second endpoint.The problem is that.With the same 'player_id',I send calls for both end points.The first one sends a response successfuly.While the second endpoint says 'Not Found'.I gather that it might be that the type of parameter im making the request with are not proper for the 2nd endpoint.
Any help regarding this is appriciated thank you.
There is a formal definition here
But sometimes it's easier to see an example, consider https://stackoverflow.com/questions/62362966/?arg=3;other=word This is composed of several parts:
https - this is the scheme
stackoverflow.com - this is the hostname
questions/62362966/ - this is the path
arg=3;other=word - this is the query
Note that where your documentation above refers to a value appearing in a path or query, that does not mean it exclusively constitutes the path or query - there is also data/meta-data framing it.
Path and query - different parts of the URL. Basically, everything that goes after ? is query, everything between domain and ? is path.
See details here
In example below I mean the user_id is a path.
https://www.example.com/api/v2/users/{user_id}
https://www.example.com/api/v2/users/11
In example below I mean the limit and the page is a query.
https://www.example.com/api/v2/users?limit={limit_value}&page={limit_value}
https://www.example.com/api/v2/users?limit=50&page=1
A query goes after ? AND is made up of a key and a value in the form key=value. Each pair is separeted by a &.
A path is what goes after the first slash (/) and before ?. It doesn't require the key-value pattern. You just put the value in the right spot (i.e. between other slashes).

Best way to get file based on url in node?

I'm new to node and am trying to figure out what the best method is for using the URL path to read the corresponding HTML document. I know how to parse the URL, and I could just open the document with the exact name as the pathname (i.e. to open index.html, you use /index.html) but personally I think it looks sloppy to end a URL with ".html" after there is already a ".com".
Essentially, my question is: how do I match the string that I get from the URL parse to a separate string that I will use to call the html file?
My only idea is to use arrays: either const home = ['/home', 'index.html']; const about = ['/about', 'about.html'] or const paths = ['/home', '/about']; const files = ['index.html', 'about.html'] and then match the string I get to the corresponding array value. I suppose this wouldn't be too terrible, but there must be a better way, right?

django modify request parameters in templates

So I wrote an app that returns an the query results. Let's assume the query URL is /query/?A=a&B=b
And now I want to add a "sort by" button to my results page to allow the users to sort the results by time, or type. Essentially just allow user to visit /query/?A=a&B=b&sorted=time or /query/?A=a&B=b&sorted=type
The easiest way is to append sorted= after the current URL. For example <a href = "{{ request.get_full_path }}&sorted=time"> But the problem is that if user first sorts by time, then sorts by type, you will have /query/?A=a&B=b&sorted=type&sorted=time
I suppose I can do some fancy string operations, but I don't know if I can do that in django template language, and I suppose there is a better way of doing it. There should be somewhere I can just modify the GET request and let the page refresh.
Thanks a lot!
You might want to look at django-tables2's solution (you might just want to look at django-tables2 in general if you're displaying this data in a table).
Two GET variables with the same name is ambigious. You can define different varaibles for the different types of sorting. Sorting has two options either ascending or descending depending on the context, you also need those values so that user can go back to the default sorting.
/query/?A=a&B=b&sort_type=asc&sort_time=desc
Then in view:
sort_type = request.GET.get('sort_type', '')
sort_time = request.GET.get('sort_time', '')
qs = MyModel.objects.all()
if sort_type:
if sort_type == 'asc':
qs = qs.order_by('type')
elif sort_type == 'desc':
qs = qs.order_by('-type')
# same goes with sort_time
# ...
# pass sort_type and sort_type or all get variables in the context to generate url in template
Now in template:
<a href = "{{ request.get_full_path }}?&sort_time={{sort_time}}&sort_type={{sort_type}}">

How to get parameter from hash url?

On some of my pages, I have a hash in the url like this: http://localhost/#/products/6959
How can I check if I have a product ID available and so I can save it in a variable to use later? Any help would be greatly appreciated!
You want a regexp to extract the number at the end of the url in javascript?
"http://localhost/#/products/6959".match(/[0-9]+$/);
Edit: Or if you want to make sure this is products:
"http://localhost/#/products/6959".match(/products\/([0-9]+$)/)[1]);
The parenthesis indicate a matching group that you find in [1].
You should be able to get that id out of the URL through accessing the params variable. In this case, params[:id] should do the trick.
Also, I do not recommend using a regex.

Categories

Resources