Can Google Apps Script handle HTTP DELETE requests? - http

It handles GET and POST requests just fine, via the respective doGet() & doPost() request handler functions. But what about DELETE requests? Is there some kind of implementation of a doDelete() function? My particular use case requires that I can send and receive a response from a DELETE request, in addition to POST and GET.

According to https://developers.google.com/apps-script/guides/web there is no doDelete or something similar, only doPost and doGet.

According to docs DELETE request works fine.
This is how I use it in my project
const params = {
"method": "DELETE",
"headers": this.getAuthHeader(),
"payload": JSON.stringify(payload)
};
const responseString = UrlFetchApp.fetch(this.getBaseUrl() + url, params);
if (responseString.getResponseCode() === 200) {
return JSON.parse(responseString);
}

Related

How do I set headers on Flutter/Dart http Request object?

I need a way to set the headers of the dart http Request object to application/JSON.
I want to build a Request object to send to my backend API. I set the body to my JSON object, but when it gets sent, it defaults the headers to text/html instead of application/json.
I have tried using the built-in method
http.post(url,dynamic body);
but unfortunately this method places the body in the parameters of the URL and I need it in the actual body of the request.
So instead I built an http Request object, and manually set the URL and body but like I said, it sets the headers to text/html.
I have read the docs for https://pub.dev/documentation/http/latest/http/Request-class.html, but unfortunately, I haven't found a way to set the headers.
postRequest(uri) async {
Uri url = Uri.tryParse("https://ptsv2.com/t/umt4a-1569012506/post");
http.Request request = new http.Request("post", url);
request.body = '{mediaItemID: 04b568fa, uri: https://www.google.com}';
var letsGo = await request.send();
print(letsGo.statusCode);
}
Much thanks for any possible solutions!
Ps. this is my first ask on Stack Overflow so I apologize if I made any errors in posting.
Solved!
postRequest(uri) async {
Uri url = Uri.tryParse("https://ptsv2.com/t/umt4a-1569012506/post");
http.Request request = new http.Request("post", url);
request.headers.clear();
request.headers.addAll({"content-type":"application/json; charset=utf-8"});
request.body = '{mediaItemID: 04b568fa, uri: https://www.google.com}';
var letsGo = await request.send();
print(letsGo.statusCode);
}
I was having some issues with the Request object default setting the encoding.
By manually specifying utf-8, the server I am contacting accepts it.
for the post or get any request you can Add Header like this -
var permAddUrl = 'your requested url';
var bodyParameters = {
'Email': email,
'MobileNo': mobileNumber,
};
await http.post(
requesturl,
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
"Authorization":"$token",
},
body: bodyParameters,).then((response) {
var data = json.encode(response.body);
print(data);
setState(() {
if(response.statusCode == 200){
//var statesList = data['data'];
UtilAction.showSnackBar(context, " Details Submitted Successfully");
}
});
});

Nativescript http post failing with no exception thrown

I am trying to call an api and post a simple json string. when debugging using VS Code, the function appears to work but nothing is returned. I suspect I don't have the headers correct. Here is my code:
{return this.http.post(
url,
content,
{ headers: this.getCommonHeaders() }
).pipe(
map(response => response.json()),
tap(data => {
console.log(data.systemAssignId)
this.san = data.systemAssignId
}),
catchError(this.handleErrors)
);}
The getCommonHeaders function looks like this:
getCommonHeaders() {
let headers = new Headers();
headers.append("Authorization", "Bearer "+ Config.token.toString().trim);
headers.append("Content-type", "application/json")
return headers;
}
I've been struggling with this for hours now. I must be missing something fundamental but cannot seem to catch it. The API works fine from Postman.
You should use HttpClient instead of Http module which was deprecated long back. With HttpClient the default response format is JSON.

How to correctly set Http Request Header in Angular 2

I have an Ionic 2 application using Angular 2, which is sending an Http PUT to a ASP.NET Core API server. Here's the method I'm using to send the request:
public update(student: Student): Promise<Student>
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);
const url = `${this.studentsUrl}`;
return this.http
.put(url, JSON.stringify(student), { headers: headers })
.toPromise()
.then(() => student)
.catch(this.handleError);
}
I'm setting an authentication key/value on the headers object.
But when I receive this request on the server, I cannot find the authentication key on the header:
As you can see in the picture, there are many keys on the header, but not the content and authentication keys that I manually added to the header in the client application.
What am I doing wrong?
Your parameter for the request options in http.put() should actually be of type RequestOptions. Try something like this:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);
let options = new RequestOptions({ headers: headers });
return this.http
.put(url, JSON.stringify(student), options)
Angular 4 >
You can either choose to set the headers manually, or make an HTTP interceptor that automatically sets header(s) every time a request is being made.
Manually
Setting a header:
http
.post('/api/items/add', body, {
headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
})
.subscribe();
Setting headers:
this.http
.post('api/items/add', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe()
Local variable (immutable instantiate again)
let headers = new HttpHeaders().set('header-name', 'header-value');
headers = headers.set('header-name-2', 'header-value-2');
this.http
.post('api/items/add', body, { headers: headers })
.subscribe()
The HttpHeaders class is immutable, so every set() returns a new instance and applies the changes.
From the Angular docs.
HTTP interceptor
A major feature of #angular/common/http is interception, the ability to declare interceptors which sit in between your application and the backend. When your application makes a request, interceptors transform it before sending it to the server, and the interceptors can transform the response on its way back before your application sees it. This is useful for everything from authentication to logging.
From the Angular docs.
Make sure you use #angular/common/http throughout your application. That way your requests will be catched by the interceptor.
Step 1, create the service:
import * as lskeys from './../localstorage.items';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '#angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '#angular/common/http';
#Injectable()
export class HeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (true) { // e.g. if token exists, otherwise use incomming request.
return next.handle(req.clone({
setHeaders: {
'AuthenticationToken': localStorage.getItem('TOKEN'),
'Tenant': localStorage.getItem('TENANT')
}
}));
}
else {
return next.handle(req);
}
}
}
Step 2, add it to your module:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HeaderInterceptor,
multi: true // Add this line when using multiple interceptors.
},
// ...
]
Useful links:
Interceptor not working properly.
APP_INITIALIZER not working in combination with interceptor
For us we used a solution like this:
this.http.get(this.urls.order + '&list', {
headers: {
'Cache-Control': 'no-cache',
}
}).subscribe((response) => { ...
Reference here
We can do it nicely using Interceptors. You dont have to set
options in all your services neither manage all your error responses,
just define 2 interceptors (one to do something before sending the
request to server and one to do something before sending the server's
response to your service)
Define an AuthInterceptor class to do something before sending the request to the server. You can set the api token (retrieve it from localStorage, see step 4) and other options in this class.
Define an responseInterceptor class to do something before sending the server response to your service (httpClient). You can manage your server response, the most comon use is to check if the user's token is valid (if not clear token from localStorage and redirect to login).
In your app.module import HTTP_INTERCEPTORS from '#angular/common/http'. Then add to your providers the interceptors (AuthInterceptor and responseInterceptor). Doing this your app will consider the interceptors in all our httpClient calls.
At login http response (use http service), save the token at
localStorage.
Then use httpClient for all your apirest services.
You can check some good practices on my github proyect here
This should be easily resolved by importing headers from Angular:
import { Http, Headers } from "#angular/http";
You have a typo.
Change: headers.append('authentication', ${student.token});
To: headers.append('Authentication', student.token);
NOTE the Authentication is capitalized
The simpler and current approach for adding header to a single request is:
// Step 1
const yourHeader: HttpHeaders = new HttpHeaders({
Authorization: 'Bearer JWT-token'
});
// POST request
this.http.post(url, body, { headers: yourHeader });
// GET request
this.http.get(url, { headers: yourHeader });

nativescript authenticating at backend web api

I am new to mobile development. My project is build using asp.net. For authentication I am using build it UserManager & User.Identity.
I have bunch of existing web apis and I wish to use them from mobile app.
I know , I could pass a secret hash to web api after authenticating, but that would involve a huge code refactoring.
I been wondering if there other ways to handle authentication & authorization with nativescript & asp.net .
Do you know any useful resources for this topic?
Many thanks for your help!
It depends quite heavily on your API structure, but I would recommend somethign like this:
Firstly you would need to use the Nativescript Http module. An implementation to get a an HTTP GET calls returned header might look like this:
http.request({ url: "https://httpbin.org/get", method: "GET" }).then(function (response) {
//// Argument (response) is HttpResponse!
//for (var header in response.headers) {
// console.log(header + ":" + response.headers[header]);
//}
}, function (e) {
//// Argument (e) is Error!
});
So your backend might return a JSON Web Token as a header. In which case on the success callback you would probably want to store your token in the applications persistent memory. I would use the Application Settings module, which would look something like:
var appSettings = require("application-settings");
appSettings.setString("storedToken", tokenValue);
Then before you make an API call for a new token you can check if there is a stored value:
var tokenValue = appSettings.getString("storedToken");
if (tokenValue === undefined {
//do API call
}
Then with your token, you would want to make an API call, e.g. this POST and add the token as a header:
http.request({
url: "https://httpbin.org/post",
method: "POST",
headers: { "Content-Type": "application/json", "Auth": tokenValue },
content: JSON.stringify({ MyVariableOne: "ValueOne", MyVariableTwo: "ValueTwo" })
}).then(function (response) {
// result = response.content.toJSON();
// console.log(result);
}, function (e) {
// console.log("Error occurred " + e);
});
Your backend would need to check the Auth header and validate the JWT to decide whether to accept or reject the call.
Alternatively, there some nice plugins for various Backends-as-a-Service, e.g. Azure and Firebase

AngularJS - Unknown provider configuring $httpProvider

In the following code example:
myApp.config(['$httpProvider', function($httpProvider, $cookieStore) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.get['Authorization'] = 'Basic '+ $cookieStore.get('myToken');
return JSON.stringify(data);
}]);
I get an angularjs error like 'Unknown provider $cookieStore'.
'myApp' has dependenciy and 'ngCookies' and angular-cookies.min.js is laoded, so what's wrong with that code ?
Is that fact that i'm doing this in .config ?
Because it's only possible to pass providers when configuring, i have finally done the overwrite of my http parameter not with a request transformer but by creating a service as factory to do requests.
Here is a code example of the service (not tested, just for information):
angular.module('myapp-http-request', []);
angular.module('myapp-http-request')
.factory('MyRequests', function($http, $cookieStore){
return {
request: function(method, url, data, okCallback, koCallback){
$http({
method: method,
url: url,
data: data
}).success(okCallback).error(koCallback);
},
authentifiedRequest: function(method, url, data, okCallback, koCallback){
$http({
method: method,
url: url,
data: data,
headers: {'Authorization': $cookieStore.get('token')}
}).success(okCallback).error(koCallback);
}
}
});
And example of usage (not tested, just for information):
angular.module('sharewebapp', ['myapp-http-request'])
.controller('MyController', ['MyRequests', function(MyRequests){
MyRequests.authentifiedRequest('DELETE', '/logout', '', function(){alert('logged-out');}, function(){alert('error');})
}]);
You probably need to add the cookieStore
myApp.config(['$httpProvider', '$cookieStore', function($httpProvider, $cookieStore)
I had ran into this same problem so i'll post how I got around it. I essentially used the $injector module to manual grab an instance of the service I needed. Note this also works for user defined services.
angular.module('app').
config(config);
config.$inject = ['$httpProvider'];
function config($httpProvider) {
//Inject using the $injector
$httpProvider.interceptors.push(['$injector', function($injector){
return {
request: function(config) {
//Get access by injecting an instance of the desired module/service
let $cookieStore = $injector.get('$cookieStore');
let token = $cookieStore.get('your-cookie-name');
if (token) {
config.headers['x-access-token'] = token;
}
return config;
}
}
}])
}
Using the Module.run() seems to be a cleaner way to set headers that are always needed. See my answer here: AngularJS pass requestVerificationToken to a service

Resources