Trying to get variable from http://localhost:3000/categories/subcategories?category_id=13 but req.query returns empty result.
app.get('/subcategories', (req, res) => {
let category_id = req.query.category_id
console.log(req.query)
db.query('SELECT subcategory_name FROM subcategories WHERE category_id=(?)',
[category_id],
(err, result) =>{
res.send({category_id})
});
})
Is this possibly a problem with the way I've set up my server?
See how you are passing the data , directly entering the data or from another URL you are passing the data.
Ensuring you are not sending data via req.body. Ref :
Empty req.query on ExpressJS
or check res.send({category_id}) . Try printing res.send({"category_id": category_id}) . or see console.log(JSON.stringify(req.query))
Or Extract Query Parameters Without Express
const url = require('url');
const querystring = require('querystring');
let rawUrl = 'https://stackabuse.com/?page=2&limit=3';
let parsedUrl = url.parse(rawUrl);
let parsedQs = querystring.parse(parsedUrl.query);
https://stackabuse.com/get-query-strings-and-parameters-in-express-js/
Related
I want to get the number from the URL located in an API response.
For that I get the URL, but I don't know how to convert that in to text to extract the number.
cy.intercept('GET', 'http://viasphere.localhost/documents/page_elements/client/**',).as('response')
goTo.plusClientsButton()
cy.wait('#response', {timeout: 10000})
cy.get('#response').then( xhr => {
const link = xhr.request.headers.referer
cy.log(link)
link has the value: http://viasphere.localhost/documents/page_elements/client/19537
Obviosly const link = xhr.request.headers.referer.text() is not working...
You have to add .replace(/^\D+/g, '') to extract the number from the url.
cy.intercept(
'GET',
'http://viasphere.localhost/documents/page_elements/client/**'
).as('response')
goTo.plusClientsButton()
cy.wait('#response', {timeout: 10000})
cy.get('#response').then((xhr) => {
const client_id = xhr.request.headers.referer.replace(/^\D+/g, '')
cy.log(client_id) //prints 19537
})
Alternatively to the .then() Alapan Das provided, you can use cypress commands to perform the same actions.
cy.intercept('GET', 'http://viasphere.localhost/documents/page_elements/client/**',).as('response')
goTo.plusClientsButton()
cy.wait('#response', {timeout: 10000})
// can access request.headers.referer from .wait()
.its('request.headers.referer')
// returns 'http://viasphere.localhost/documents/page_elements/client/'
.invoke('replace', /^D+/g, '')
// now you have the link and can print it
.then(cy.log)
I have to validate two fields are equals. In this case both passwords are the same. The problem it is that the "equals" from express-validator is not working.
This is the code:
app.post('/register', [
isNotLogged,
check('email', 'The email must be a valid one').isEmail(),
check('nickname', 'The nickname must be filled').notEmpty(),
check('password', 'The password must contain minimum eight characters, at least one letter and one number')
.matches("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"),
//This is not working
check('passwordConfirm', 'The passwords must match').equals('password'),
validateResults
], register)
Unfortunately Express-Validator doesn't work with Validator.js's equals(), you'll have to use one of Express-Validator's middlewares and not its Validator.js affility.
Here is an example straight from Express-Validator's website which seems fit your use case:
body('oldPassword')
// if the new password is provided...
.if((value, { req }) => req.body.newPassword)
// OR
.if(body('newPassword').exists())
// ...then the old password must be too...
.notEmpty()
// ...and they must not be equal.
.custom((value, { req }) => value !== req.body.newPassword);
You do not need to use Express-Validator's check middleware as you are throwing away your ability to utilise Validator.js's validators. Instead of check you could use isEmail() and exists() (an Express-Validator validator). Also, you don't need to have your middlewares as part of an array (although you can):
app.post('/register',
isNotLogged,
body('email').isEmail().withMessage('The email must be a valid one').bail().trim(),
body('nickname').exists({ checkNull: true }).withMessage('The nickname must be filled').bail().trim(),
body('password').trim().if((value, { req }) => (typeof req.body.passwordConfirm !== 'undefined')).bail().custom((value, { req }) => value !== req.body.passwordConfirm).withMessage('The email must be a valid one').bail().trim().matches("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$"),
validateResults,
register
);
Here the body() function would come from const { body } = require('express-validator') theres a few others similar for query paramaters, header parameters ect, all are documented here.
I also used some trim()s and bails()s just to be safe. You can read up on those here and here.
I solve this problem like this:
code before:
const registrar = async (req, res) => {
await check('password').isLength({ min:6}).withMessage('password short ').run(req);
await check('repetir_password').equals('password').withMessage('password diferente?').run(req);
let resultado = validationResult(req);
res.json(resultado.array());
};
after:
correct code: change
'password'
by
req.body.password
const registrar = async (req, res) => {
await check('password').isLength({ min: 6 }).withMessage('password corta ').run(req);
await check('repetir_password').equals(req.body.password).withMessage('password diferente?').run(req);
let resultado = validationResult(req);
res.json(resultado.array());
};
I have an array of users as below
let usersarr = ["'SAC_XSA_HDB_USER_ABC','SAC_XSA_HDB_USER_DEF'"]
I want to fetch data about the above users(if exists) from Hana database. I am using sap-hdbext-promisfied library in node.js.
My database connection is working fine. So, I am trying to execute a select query as below
async function readUsers(xsaDbConn){
try{
let usersarr = ["'SAC_XSA_HDB_USER_ABC','SAC_XSA_HDB_USER_DEF'"]
const checkuserexiststatement = await xsaDbConn.preparePromisified("SELECT USER_NAME FROM USERS WHERE USER_NAME IN (?)")
let checkuserexistresult = await xsaDbConn.statementExecPromisified(checkuserexiststatement, [usersarr])
console.log(checkuserexistresult)
return checkuserexistresult
}catch(err){
console.log(err)
return;
}
}
Below is the output I get
PS C:\Users\Documents\XSA\SAC_POC\cap_njs> npm start
> cap_njs#1.0.0 start C:\Users\Documents\XSA\SAC_POC\cap_njs
> node server.js
myapp is using Node.js version: v12.18.3
myapp listening on port 3000
[]
I get an empty array object as output. This is not the expected output, instead it should provide details about the users as they exist in the database.
The above code works when I provide single user value instead of multiple users in an array as shown below
async function readUsers(xsaDbConn, tempxsahdbusers){
try{
let usersarr = 'SAC_XSA_HDB_USER_ABC'
const checkuserexiststatement = await xsaDbConn.preparePromisified("SELECT USER_NAME FROM USERS WHERE USER_NAME IN (?)")
let checkuserexistresult = await xsaDbConn.statementExecPromisified(checkuserexiststatement, [usersarr])
console.log(checkuserexistresult)
return checkuserexistresult
}catch(err){
console.log(err)
return;
}
}
Output Of Above Code -
PS C:\Users\Documents\XSA\SAC_POC\cap_njs> npm start
> cap_njs#1.0.0 start C:\Users\Documents\XSA\SAC_POC\cap_njs
> node server.js
myapp is using Node.js version: v12.18.3
myapp listening on port 3000
[ 'SAC_XSA_HDB_USER_ABC' ]
So, why is it giving an empty array object when I provide an array as a parameter instead of a variable? Is it possible to provide an array as a parameter to the function statementExecPromisified(statement, []) of sap-hdbext-promisfied library in node.js ?
Your
let usersarr = ["'SAC_XSA_HDB_USER_ABC','SAC_XSA_HDB_USER_DEF'"]
has exactly one value, the String:
"'SAC_XSA_HDB_USER_ABC','SAC_XSA_HDB_USER_DEF'"
When passing the userarr in the statementExecPromisified function as a parameter you are actually passing a nested array in an array. You could either try
xsaDbConn.statementExecPromisified(checkuserexiststatement, [usersarr[0]])
or separate the values in the userarr and add multiple ? in the prepared statement and reference each single value with userarr[x].
As i can get the query params by using ActivatedRoute which is get request. but how can i get request body by using ActivatedRoute from post request. If ActivatedRoute is not right option to get then how should i get request body
This is my jsp code:-
var res = "url which i am creating";
var url =res[0];
var mapForm = document.createElement("form");
mapForm.target = "Test";
mapForm.method = "post";
mapForm.action = url;
//Splitting parameters from url to add into body
var res1 =res[1].split("=");
var name = res1[0];
var value = res1[1];
mapInput3 = document.createElement("input");
mapInput3.type = "hidden";
mapInput3.name =name;
mapInput3.value = value;
mapForm.appendChild(mapInput3);
document.body.appendChild(mapForm);
map = window.open("", "Test", "menubar,
toolbar, location, directories, status, scrollbars,
resizable, dependent, width=1200, height=600,
left=0,top=0");
if (map) {
mapForm.submit();
}
this is my angular code:-
this.activeRoute.queryParams.subscribe(params => {
this.authKey = params['auth_key'];
});
Now if I sent parameter through get method from jsp, I am able to get it from above angular code.
but if i sent params through post method then i get message as " Cannot post"
If I got you right you want to get the body of the query.
You can use snapshot.get and when declare a it with a value something like this ->
const t = this.route.snapshot.mapedQuery.get()
The value of- t is your query body.
Answered from my phone so I can’t format the code
I am trying to incorporate the BTC-e.com API in to a google docs spreadsheet.
The API documentation is here: https://btc-e.com/api/documentation
The method name is sent via POST parameter method.
As the URLFetchApp requires me to set the type of request as POST by a parameter method and I then have another parameter called method to be set as getInfo.
How can I go about setting the fetch method as POST and have the API parameter method as getInfo.
Below is the function this relates too. Also I am sure there a more issues in my work I am yet to find.
function inventory() {
var nonce=Number(SpreadsheetApp.getActiveSheet().getRange('K2').getValue());
var token=SpreadsheetApp.getActiveSheet().getRange('K1').getValue();
var tokenEndpoint = "https://btc-e.com/tapi";
var sign= 'TEMP'
var head = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': token,
'Sign': sign
}
var params = {
method : "POST",
method : "getInfo",
headers: head,
contentType: 'application/x-www-form-urlencoded',
method : "getInfo",
nonce: nonce
}
var request = UrlFetchApp.getRequest(tokenEndpoint, params);
var response = UrlFetchApp.fetch(tokenEndpoint, params);
var response2=String(response);
SpreadsheetApp.getActiveSheet().getRange('K2').setValue(nonce+1);
SpreadsheetApp.getActiveSheet().getRange('I16').setValue(response2);
SpreadsheetApp.getActiveSheet().getRange('I17').setValue(nonce);
}
This just yields the error
Attribute provided with invalid value: method
Thanks,
Steve
PS: First time posting, I tried to get the format correct.
I made the following Google JavaScript function to do POST access to BTC-e. You can find this function in action in the example spreadsheet I made to demonstrate the BTC-e API functions.
function btceHttpPost(keyPair, method, params, nonce) {
if (keyPair === undefined) {
return "{'error':'missing key pair'}"
}
if (params === undefined) {
params = '';
}
// Cleanup keypair, remove all \s (any whitespace)
var keyPair = keyPair.replace(/[\s]/g, '');
// Keypair example: "AFE730YV-S9A4FXBJ-NQ12HXS9-CA3S3MPM-CKQLU0PG,96a00f086824ddfddd9085a5c32b8a7b225657ae2fe9c4483b4c109fab6bf1a7"
keyPair = keyPair.split(',');
var pubKey = keyPair[0];
var privKey = keyPair[1];
// As specified on the BTC-e api (https://btc-e.com/api/documentation) the
// nonce POST parameter must be an incrementing integer (>0). The easiest
// implementation is the use of a timestamp (TS), so there is no need
// for persistant storage. Preferable, the resolution of the TS should be
// small enough the handle the desired call-frequency (a sleep of the TS
// resolution can fix this but I don't like such a waste). Another
// consideration is the sizeof the nonce supported by BTC-e. Experiments
// revealed this is a 32 bit unsigned number. The native JavaScript TS,
// stored in a float, can be 53 bits and has a resolution of 1 ms.
if (nonce === undefined)
// This time stamp counts amount of 200ms ticks starting from Jan 1st, 2014 UTC
// On 22 Mar 2041 01:17:39 UTC, it will overflow the 32 bits and will fail
// the nonce key for BTC-e
var nonce = Math.floor((Date.now() - Date.UTC(2014,0)) / 200);
// Construct payload message
var msg = 'nonce=' + nonce + '&method=' + method + params;
var msgSign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, msg, privKey);
// Convert encoded message from byte[] to hex string
for (var msgSignHex = [], i = 0; i < msgSign.length; i++) {
// Doing it nibble by nibble makes sure we keep leading zero's
msgSignHex.push(((msgSign[i] >>> 4) & 0xF).toString(16));
msgSignHex.push((msgSign[i] & 0xF).toString(16));
}
msgSignHex = msgSignHex.join('');
var httpHeaders = {'Key': pubKey, 'Sign': msgSignHex};
var fetchOptions = {'method': 'post', 'headers': httpHeaders, 'payload': msg};
var reponse = UrlFetchApp.fetch('https://btc-e.com/tapi', fetchOptions);
return reponse.getContentText();
};
The problem looks to be with your params object . You have method set thrice in the same object, which is a source of confusion.
Next, take a look at the documentation for UrlFetchApp.fetch() ( https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object) ) . The method can take a value of post, get, delete, put.
The getInfo should probably be appended to your URL to make it
var tokenEndpoint = "https://btc-e.com/tapi/getInfo"
Per the docs, you also have to put in more parameters to the request, nonce, api key etc. Use this as a starting point, revisit the documentation and get back to SO if you still have trouble