Next js - How to pass multiple parameters in url for api? - javascript

I am able to pass one parameter and get results from next js api
The docs are very helpful - https://nextjs.org/docs/api-routes/dynamic-api-routes
/api/posts/[postId].js
The above works but is there an option to pass another parameter like below?
/api/posts/[postId][userId].js
The folder name is currently [postId]. I tried renaming it to [postId][userId]
My code for api is
let postVotes = await req.db.collection('votesPosts').count({"post":req.query.postId,"user":req.query.userId})

Usually, routes don't handle multiple parameters in a single segment of the URL path. You can only have one parameter per segment:
/api/entity/{param1}/{param2}/sub/{param3}
Now in Next JS, you need to separate them too to have 2 segments with param:
/api/posts/[postId]/[userId]
Which would resolve to 2 possible files:
/api/posts/postId]/[userId]/index.js
if you do it with a parameter directory + index file, or
/api/posts/postId]/[userId].js
if you do it with a parameter file.
Doing it with directory + index file allow you to add fixed segments like:
/api/posts/postId]/[userId]/popular.js
/api/posts/postId]/[userId]/private.js
Then you can make your API call as you did it for 2 params.

Related

Understanding htaccess and $_GETs

This is how my site is constructed...
articles.php contains the layout html to display all articles for a category.
articles.js contains the control elements to obtain db query results and pass to articles.php page. Within the js script is a dataTable that is displayed on the articles.php page.
ajax_articles.php contains the query request and return json file results of the query. Within the json file are links to the individual articles. The link is structured as a clean SEO URL (e.g., article/001/moby_dick).
This is how I understand htaccess to work.
When a user selects an article the URL (i.e., https://www.example.com/article/001/moby-dick) is passed through htaccess and with a RewriteRule ^article/([0-9]+)/([a-z_-]+) article.php?art_id=$1&art_name=$2 [NC,L] will display the SEO 'pretty' URL, BUT known to the system will be the URL containing the two parameters that can be used by a $_GET to obtain the two parameters. IS MY UNDERSTANDING OF THE PROCESS CORRECT?
I've noticed that with the htaccess I now have to use the full path name to load the support (.js) and graphic files. Further, I cannot obtain the variables via js $_GET.art_id and $_GET.art_name.
Any assistance is greatly appreciated.
You can't access the GET variables with javascript in this configuration because they do not exist after the URL rewrite. The query parameters have been removed.
There are still ways you can extract these values from the URL with window.location.href and the .split() method in javascript.
// var myurl = window.location.href; // this will get the string of your current URL. Used manual string in this example
var myurl = "https://www.example.com/article/001/moby-dick"; // manual URL for sake of an executable example
var spliturl = myurl.split("/"); // ["https:","","example.com","article","001","moby-dick"]
var articleid = spliturl[4]; // "001"
var articlename = spliturl[5]; // "moby-dick"
// see the variables in action
console.log("id: ", articleid);
console.log("name: ", articlename);

Passing only the required rows of data from CSV file to Jmeter based on a criteria

I have a csv file which has the input in the below format (It has no headers as first row):
India,QA,1200,
India,QA1,1201,
India,QA2,1202,
USA,Dev1,5580,
USA,Dev2,5580,
AUS,Dev3,3300,
AUS,Dev4,3301,
I have configured the CSV Data Set Config component and have given the respective path and variable name details. Snapshot below:
from the command line argument, i will be invoking the Jmeter jmeter.bat -t C:\Users\Dev\Desktop\JI\testscript.jmx -JCountry=Indiawhich also has a parameter called JCountry=India.
Now, I have to use this value (India) and then search the csv file's first column and if it matches, I need to send only those particular rows matching to the country name given from the cmd to the script.
I thought of using If Controller but how can I check the csv files first row and when there is a match, send those details to the script.
The easiest option would be dynamically generating a CSV file with only India lines
Add setUp Thread Group to your Test Plan
Add Test Action sampler to the setUp Thread Group (this way you won't have an extra result in .jtl file)
Add JSR223 PreProcessor as a child of the Test Action Sampler
Put the following code into "Script" area:
String country = props.get('Country')
def originalCsvFile = new File('C:/Users/Dev/Desktop/JI/JVMDetails/Details.txt')
def countryCsvFile = new File('C:/Users/Dev/Desktop/JI/JVMDetails/Country.txt')
countryCsvFile.delete()
originalCsvFile.eachLine {line ->
if (line.startsWith(country)) {
countryCsvFile << line
countryCsvFile << System.getProperty('line.separator')
}
}
Configure your CSV Data Set Config to use C:\Users\Dev\Desktop\JI\JVMDetails\Country.txt as this file will have only those lines which start with what you have defined as Country property
More information:
Apache Groovy - Why and How You Should Use It
Groovy Goodness: Working with Files
You need to loop through CSV, see example or other examples.
As the second example use in while condition the variable from CSV: ${Country} .
Inside loop you need to add If Controller with condition to compare country variable against country property:
${__jexl3("${__P{Country}" == "${Country}")}
Checking this and using __jexl3 or __groovy function in Condition is advised for performances

Add parameter to rails3-jquery-autocomplete (now rails-jquery-autocomplete) in addition to "term"

When autocomplete sends the query string it contains a parameter of term. See here:
Started GET "/nodes/autocomplete_user_first_name?term=Mi" for 127.0.0.1
Processing by NodesController#autocomplete_user_first_name as JSON
Parameters: {"term"=>"Mi"}
I need to add a parameter to a value that's available in my view to yield something like this, using node as the parameter and 27 as the value:
Started GET "/nodes/autocomplete_user_first_name?term=Mi&node=27"
Processing by NodesController#autocomplete_user_first_name as JSON
Parameters: {"term"=>"Mi", "node" => 27}
If I have to add via jQuery is a javascript file, please tell me where it should go. I'm new to js/JQuery, but I understand it. Thanks!
EDIT
The reason I need the node param is because I need to restrict the scope based on its value.
def get_autocomplete_items(parameters)
items = active_record_get_autocomplete_items(parameters)
items = items.where(:id => current_user.family_tree.memberships.pluck(:user_id))
.where.not(:full_name => node.user_tags.pluck(:name))
end

Node JS - Express.js get query with multiple parameters

I'm quite new to JavaScript and Node JS and I have a such a situation. When I try to call get of express.js with a single parameter everything works fine, but when I try to call get with more than one parameter, it trims the query.
For example I have such call and function
app.get('path/data', myFunc);
// in another file
function myFunc(req, res) {
// do some stuff
}
When the url is path/data?id=5 or path/data?name=foo everything is fine. But when I use for example url like path/data?id=5&name=foo in myFunc I get url as path/data?id=5. So I get url's first part - what is before & sign.
Now what am I doing wrong? Is there something that I'm missing? How can I get whole url in myFunc without being trimmed?
Use
app.get('path/data?:id?:name')
And for retrieving the values, use req.query.id and req.query.name.
For accessing the REST api, you need to hit:
http://localhost:8080/demo?id=3&name=stack
So, by this you can add multiple parameters in your api.
Hope this helps.
I found the problem. I was requesting via curl and it turns out that shell command trims in case of there is an & in the url. So there is a need no add quotes like this
curl "path/data?id=5&name=foo"

plupload - send another request parameter with uploaded file

plupload creates nice ids in file object. How this id can be sent to the upload script?
The upload script has 3 variables in $_POST - file name, chunk number and total number of chunks.
How to add another parameter to plupload's POST request (in my case, the file.id)?
The first step would be to add a handler to the BeforeUpload event.
Then, if you are using multipart, you can change the uploader settings to dynamically set different multipart params:
plupload_instance.bind('BeforeUpload', function (up, file) {
up.settings.multipart_params = {fileid: file.id}
});
(warning: this example overrides any and all multipart_params, you can play it smarter than that by just setting fileid)
if you are not using multipart, your only options would be to pass the argument as a header, or to manually add the param to the URL for each file (these 2 options should also be done within BeforeUpload).
Note that when not using multipart, plupload will add the name and chunk params to the URL after any URL you already set for the uploader, for each file, so this is where extra params go.

Categories