concatenate variable in URL.React Native - url

I am unable to concatenate state in URL. Have searched but I could not find the solution, and i'm a beginner sorry for asking such a basic question. State has the value before it is sent as a parameter in URL(i have seen it in console), API returns the expected result if I hard code the value, but if a state or even a variable is passed as a parameter it returns error: "NO records found". What am I doing wrong?
this.state.secid = this.props.navigation.state.params.secid
console.log(this.state.secid)
this.state.classid = this.props.navigation.state.params.clasid
console.log(this.state.classid)
// Sending Request
fetch('exampleapi/parameter?
class=${this.state.classid}&section=${this.state.secid}',{
headers: {
'Content-Type':'application/json',
'credentials': 'same-origin',
'Accept': 'application/json',
'Authorization': 'Bearer ' + tokenval
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ allstudents : responseJson })
console.log(this.state.allstudents)
})

You need to make following changes in your code
var url = 'exampleapi/parameter?class='+this.state.classid+'&section='this.state.secid;
fetch(url,{
headers: {
'Content-Type':'application/json',
'credentials': 'same-origin',
'Accept': 'application/json',
'Authorization': 'Bearer ' + tokenval
}
})
Concatenation in react native is done by (+) operator. As URL also a string.
Hope it works for you.

I solved this issue by using backtick notation. Replacing ' '(single quote) in URL by ``(back ticks).
If anybody wants to read more about backtick notation this is an amazing answer : What is the usage of the backtick symbol (`) in JavaScript?

From what I can see in the code added the string concatenation is not done correctly.
It should be done as explained below:
this.state.secid = this.props.navigation.state.params.secid
this.state.classid = this.props.navigation.state.params.clasid
const requestURL = `exampleapi/parameterclass=${this.state.classid}&section=${this.state.secid}`
Then, I would recommend to log and check if you are getting the URL as expected. Also I would suggest to stick to do this es6 way rather than using + for concatenation (As using + is more error prone, you might miss a space place where required - In your case the place you are setting Authorization header ).
Moreover why not use the good stuff when its supported out of the box by react native
Some references:
https://developers.google.com/web/updates/2015/01/ES6-Template-Strings#string_substitution
https://facebook.github.io/react-native/docs/javascript-environment.html
(search for text Template Literals in the page).

Related

Cypress how to use api key in put/post request?

I am trying to use AWS API and its API-key in POST/PUT call in Cypress, couldn't find enough details, can someone please help?
There are few options you can try, Here is one :
cy.intercept('POST', '/users*', (req) => {
req.headers['x-api-key'] = 'bearer my-bearer-auth-token'
}).as('addAuthHeader')
Refer Offical Link here:
https://docs.cypress.io/guides/guides/network-requests#Assertions
I was able to resovle it syntax is: authorization : key + value no quotes –
You can use cy.request. Although not outlined in the docs, it accepts an object:
cy.request({
method: 'POST',
url: 'https://jsonplaceholder.cypress.io/',
headers: { 'x-api-key': 'APIKEY' },
}).then((res) => {
// use the response with response.body
});

Google Spreadsheet Protected Web-App Access Level Anyone

I have deployed a gsheets web-app and the code executes fine if the web-app's "who has access to this" is set to "anyone, annonymous" access. below is this code.
var data = {
'command1': 'usermenu',
'command2': 'dopayroll'
};
var options = {
'method' : 'post',
'payload' : data
};
var response = UrlFetchApp.fetch(ScriptApp.getService().getUrl(), options);
getSpread().toast(response.getContentText());
What I want to do, is change the access level to "Anyone" - which is access by any authenticated google account (right?). Added the following code to "var options" but returns an error code 401. How can I make this work?
'header' : { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
EDIT; I should add that I'm a newbie in things related to OAuth and stuff.
There was a response posted which is now not visible.
My thanks to the person who did and having tested it, I can now confirm that the solution proposed works. There were 2 parts to the solution. First the correct header below ("header" should really be "headers")
'headers' : { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
and adding the following comment to trigger Drive scope access for the project.
// DriveApp.getFiles()

unclear error from dart2js checked mode

My original error was An attempt was made to use an object that is not, or is no longer, usable. After dart2js runs with the default settings it's pretty difficult to read and I was having trouble debugging the output, so I added these options to my pubspec.yaml:
- $dart2js:
checked: true
sourceMaps: true
verbose: true
minify: false
I was expecting something to break, but I was hoping the error message would be clear enough that I could work it out, but I understand the error I'm getting.
The new error I'm getting is:
Error:
dart<.wrapException()
dart<._rootHandleUncaughtError_closure.call$0()
dart<._microtaskLoop()
dart<._startMicrotaskLoop<()
dart<._AsyncRun__initializeScheduleImmediate_internalCallback.call$1<()
dart<.invokeClosure_closure0.call$0()
dart<._IsolateContext.eval$1()
dart<._callInIsolate()
dart<.invokeClosure<()
dart<.convertDartClosureToJS/$function</<()
It looks like dart is having some trouble converting a closure to a js function. I'd have thought this would be done when dart2js is run and not while the application is running in the browser.
My code doesn't have any explicit closures, but I do use async await. Am I right in assuming that those would be converted into closures?
Just in case it's relevant, I'm also using Angular2.
Update
It appears that my problems are being caused by my use of the HttpRequest.request() from dart:html.
HttpRequest res = await HttpRequest.request( "${API_URL}/login",
method : "POST",
responseType: "json",
mimeType : "application/json",
sendData : JSON.encode( req_data ) );
print( res.status );
If I remove checked mode and build this is giving me the An attempt was made to use an object that is not, or is no longer, usable error.
The API is better, more intuitive.
For example your request :
var client = new BrowserClient();
var response = await client.post("${API_URL}/login",
body: JSON.encode( req_data ));
var data = JSON.decode(response.body);
client.close();
And you could probably see in the parameters if you want more precision in the way you want to define your request.
It seems that I have fixed the problem by changing my use of the HttpRequest class.
From:
HttpRequest res = await HttpRequest.request( "${API_URL}/login",
method : "POST",
responseType: "json",
mimeType : "application/json",
sendData : JSON.encode( req_data ) );
print( res.status );
To:
HttpRequest res = new HttpRequest()
..open( "POST", "${API_URL}/login" );
req
..onLoadEnd.listen( ( ProgressEvent e ) {
print( res.status );
})
..send( JSON.encode( req_data ) );
I'm not sure what the actual problem was, but this way I don't get either the InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable or the longer dart error:
Error:
dart<.wrapException()
dart<._rootHandleUncaughtError_closure.call$0()
dart<._microtaskLoop()
dart<._startMicrotaskLoop<()
dart<._AsyncRun__initializeScheduleImmediate_internalCallback.call$1<()
dart<.invokeClosure_closure0.call$0()
dart<._IsolateContext.eval$1()
dart<._callInIsolate()
dart<.invokeClosure<()
dart<.convertDartClosureToJS/$function</<()
My guess is that dart2js is hving some trouble with async await "implicit" closures and is much happier when I use an "explicit here's a function that closes over it's environment" closure.
Thanks to Günter Zöchbauer for the help.
You should use http package instead
https://pub.dartlang.org/packages/http

Polymer <core-xhr> - no POST params sent

I'm desperately trying to send data via POST to a express.js application. The express.js app works fine but for whatever reason the POST data isn't sent to the server properly:
var xhrConfig = {
url: "http://localhost:3000/test",
body: {"foo": "bar"},
// body: JSON.stringify({"foo": "bar"}),
// body: 'foo=bar',
method: "POST"
};
document.createElement('core-xhr').request(xhrConfig);
My express.js console.log(req.body) output is always {}. No matter if body is sent stringified or raw or JSON. I also tried params instead of body just to make sure.
I tried the same in jQuery to exclude the possibility of having a bug in my express.js route but $.ajax({url: 'http://localhost:3000/test', data: {foo: 'bar'}, type: 'POST'}); works perfectly fine.
So what's the reason that req,body is always empty? Any ideas?
//edit:
body: "foo=bar",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
This one works now but is there a way to be able to use body: {"foo": "bar"} instead of converting it to foo=bar first?
As far as I know, core-xhr is a low level element, and the body object on it's conf doesn't accept a JS object but the string body you want to use.
For the use you describe, you could try core-ajax, a higher level element that can be configured with an object. Doc on core-ajax: https://www.polymer-project.org/docs/elements/core-elements.html#core-ajax.
<core-ajax
auto
url="http://localhost:3000/test"
body='{"foo": "bar"}'
handleAs="json"
method: "POST"
on-core-response="{{handleResponse}}"></core-ajax>
Hope it helps. If you need a more detailed example, don't hesitate to ask.
Looks like express looks at the Content-Type header to determine what type of body it has, below works for me.
this.$.xhr.request({
url: "/my/url",
method: "POST",
headers:{
"Content-Type":"application/json"
},
body: JSON.stringify(survey),
callback: function(response){
console.log(response);
}
});
I had this problem as well on Polymer. This problem is very frustrating because there isn't much documentation on Polymer on core-xhr.
As you have already answered the first question yourself, I'll answer the latter: yes/no. If you look at the source of <core-xhr>, it just feeds the params straight to xhr.send(params). however, there is a method inside of called toQueryString, which does what you want to do.
toQueryString: function(params) {
var r = [];
for (var n in params) {
var v = params[n];
n = encodeURIComponent(n);
r.push(v == null ? n : (n + '=' + encodeURIComponent(v)));
}
return r.join('&');
}

mootools textarea string

I want to send a Request with the content of a textarea but i get only a array instead of the wished string.
<textarea id="putup" name="textarea" cols="70" rows="15">http://www.example.com/?var=2EBR&n=1</textarea>
window.addEvent('domready', function() {
alert($('putup').value);
myRequest = new Request({
method: 'post',
url: 'build2.php',
}).post('var='+$('putup').value+'&uniquebutton='+$('uniquebutton').value);
});
my posts look like this:
Array ( [var] => http://www.example.com/?var=2EBR [n] => 1 [uniquebutton] => aqynnnisqopo )
how to get the real string?
Your code is fine except that your are trying to send a full url in your post without encoding it - which may create a problem if the url also contains parameters - like in your case it's &n=1 that is sending as post param key=>n value=>1 you need to use encodeURIComponent when u send urls and strings that might contains params chars so your param that hold this URL will include the entire URL and won't break it:
myRequest = new Request({
method: 'post',
url: 'build2.php',
}).post('var='+ window.encodeURIComponent($('putup').value)+'&uniquebutton='+$('uniquebutton').value);
and another little remark - in mootools u can use the get function of element to get any valid property of any element - so you can do $('pupup').get('value') but the classic way $('putup').value is perfectly fine of course.

Resources