I try to consume a service via post whit angular2. This my code:
var m_dataRequest = this.buildLoginUserPasswordRequest(password, key);
let headers = new Headers({
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'es-ES,es;q=0.8,en;q=0.6',
'Content-Type': 'application/x-www-form-urlencoded',
});
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
body.set("message", JSON.stringify(m_dataRequest));
body.set("webService", "authService");
return this.http
.post(this.Url, body.toString(), options)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
private buildLoginUserPasswordRequest(password:string, key:string): any {
var m_dataRequest = {
"ser:nativeAppAuth": {
"-xmlns:ser": "http://services.mobileappbc.ws.todo1.com/",
"password": this.utilService.buidRSAPass(password, t1Assertion),
"key": key,
"deviceInfo": this.utilService.getDeviceInfo()
}
};
return m_dataRequest;
}
The Content-type is application/x-www-form-urlencoded because the backend need the info of this way.
My problem is the character ":" is not convert to equivalent urlencoded %3A+.
this cause a problem in my backend service.
any Suggestion for solve this?
Thanks!
Json.stringify does not uri encode data because it can handle it.
You need to use uriencode()
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURI
Related
Dio used to allow setting default cookies in baseOptions such as this.
final BaseOptions dioBaseOptions = BaseOptions(
baseUrl: 'http://192.168.1.19',
headers: {
"Host": "api.example.test",
"Content-Type": "application/json",
},
cookies: [
Cookie('XDEBUG_SESSION', 'PHPSTORM'),
],
);
With the updated API this appears to be no longer the case and we need to go with interceptors (or there's an alternative)? Trying to adjust the above code to the new Dio API I have the following except I cannot see how to add a cookie to the jar.
var dio = Dio();
dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
var customHeaders = {
"Host": "api.example.test",
"Content-Type": "application/json",
};
options.headers.addAll(customHeaders);
return options;
}));
var cookieJar=CookieJar();
/// I was expecting something like .add(Cookie(...))
dio.interceptors.add(CookieManager(cookieJar));
Looks like the only way is to manually write the cookie in the headers
final BaseOptions dioBaseOptions = BaseOptions(
baseUrl: 'http://192.168.1.19',
headers: {
'Host': "api.radio.test",
'Content-Type': 'application/json',
'Cookie': 'XDEBUG_SESSION=PHPSTORM',
},
);
I am setting up a Zap for our application in Zapier.
However, I've run into some trouble having the Zap pass over the data in the correct format.
By default it appears Zapier passes the data as json request body, but our backend only accepts form-data.
Is it possible to configure the Zap to send over form-data instead?
In the code below, I've tried to send the data as both params and body, but my backend doesn't any of it as form-data:
const options = {
url: '${URL}',
method: 'POST',
headers: {
'Authorization': ${token},
'Content-Type': 'application/json',
'Accept': 'application/json'
},
params: {
'phone': bundle.inputData.phone,
'email': bundle.inputData.email,
'dialog': bundle.inputData.dialog,
'name': bundle.inputData.name
},
body: {
'name': bundle.inputData.name,
'email': bundle.inputData.email,
'phone': bundle.inputData.phone,
'dialog': bundle.inputData.dialog
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
// You can do any parsing you need for results here before returning them
return results;
});
Any input is greatly appreciated!
I fixed it by replacing 'Content-Type': 'application/json' with 'Content-Type': 'application/x-www-form-urlencoded'.
I have an issue with using Method.Post on my flutter app using http dart library. It seems that when I tried to post data from my WebAPI it gaves me a StatusCode 415. See my code below:
Code Login:
Future<User> login(User user) async {
print(URLRequest.URL_LOGIN);
return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: {
'username': user.username,
'password': user.password
}, headers: {
"Accept": "application/json",
}).then((dynamic res) {
print(res.toString());
});
}
Code NetworkUtils:
Future<dynamic> post(String url, {Map headers, body, encoding}) async {
return await http
.post(url, body: body, headers: headers, encoding: encoding)
.then((http.Response response) {
final String res = response.body;
final int statusCode = response.statusCode;
if (statusCode < 200 || statusCode > 400 || json == null) {
throw new Exception('Error while fetching data.');
}
return _decoder.convert(res);
});
}
Does anyone knew whats going on my code?
Try adding this new header:
headers: {
"Accept": "application/json",
"content-type":"application/json"
}
UPDATE
Ok now you need to send json data, like this :
import 'dart:convert';
var body = jsonEncode( {
'username': user.username,
'password': user.password
});
return await _netUtil.post(Uri.encodeFull(URLRequest.URL_LOGIN), body: body, headers: {
"Accept": "application/json",
"content-type": "application/json"
}).then((dynamic res) {
print(res.toString());
});
}
#Alvin Quezon
I met the same error as yours and fix it, please see below.
[Error]
StateError (Bad state: Cannot set the body fields of a Request with content-type "application/json".)
[Reason]
when you use the Flutter plug 'http.dart' method 'http.post()', you should read the document in detail below (note the black fonts):
Sends an HTTP POST request with the given headers and body to the given URL.
[body] sets the body of the request. It can be a [String], a [List<int>] or
a [Map<String, String>]. If it's a String, it's encoded using [encoding] and
used as the body of the request. The content-type of the request will
default to "text/plain".
If [body] is a List, it's used as a list of bytes for the body of the
request.
If [body] is a Map, it's encoded as form fields using [encoding]. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.
[encoding] defaults to [utf8].
For more fine-grained control over the request, use [Request] or
[StreamedRequest] instead.
Future<Response> post(Uri url,
{Map<String, String>? headers, Object? body, Encoding? encoding}) =>
_withClient((client) =>
client.post(url, headers: headers, body: body, encoding: encoding));
[Solution]
So just encode your body as a string ,then you can set the header 'content-type' as 'application/json'.
see the codes of #diegoveloper answered!
I am using Angular2 in my application, And I saw advantages of using Observable while calling http calls. But somehow I am not able to make call when I am using Observable for POST requests, But it's working while GET request. If I use subscribe method, then POST is working.
Below is my code,
using Observable,
AddBreakoutsManually(breakoutUploads: Uploads): Observable<boolean> {
console.log("Data = ", JSON.stringify(breakoutUploads));
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post("/breakout/InsertUploads", JSON.stringify(breakoutUploads), options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
Using subscribe,
Adding(breakoutUploads: Uploads) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http
.post('/breakout/InsertUploads', JSON.stringify(breakoutUploads), options)
.subscribe(data => {
alert('ok');
}, error => {
console.log(error.json());
});
}
My API,
[HttpPost]
public bool InsertUploads([FromBody]BreakoutUpload breakoutUploads)
{
return true;
}
What mistake I am making while using observable in POST call ?
Not sure what I changed, But it starts working with below code,
AddBreakoutsManually(breakoutUploads: Uploads): Observable<string> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(Configuration.Url_AddBreakoutsManually, JSON.stringify(breakoutUploads), options) // ...using post request
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
Currently I have a problem with an Angular2 and RoR5 API. I'm trying to save an object to the API Server, but this doesn't work.
Here is my Angular2 Code for the service:
createFrame(frameData) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify({frame: frameData});
return this.http.post(this.frameURL, body, headers).map((res: Response) => res.json());
}
The request is made by my browser and I can see the JSON Data:
But RoR is not able to get the POST Data.
[1] pry(#<Api::V1::FramesController>)> params
=> <ActionController::Parameters {"format"=>:json, "controller"=>"api/v1/frames", "action"=>"create"} permitted: false>
[2] pry(#<Api::V1::FramesController>)>
Can someone tell me, what's wrong?
In your case, you set the content type for form data and you send some content with the JSON format.
Either you use send form data or JSON content.
Form data
createFrame(frameData) {
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let form = new URLSearchParams();
form.set('param1', 'some value');
let body = form.toString();
return this.http.post(this.frameURL, body, headers).map((res: Response) => res.json());
}
JSON data
createFrame(frameData) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let form = new URLSearchParams();
form.set('param1', 'some value');
let body = form.toString();
return this.http.post(this.frameURL, body, headers).map((res: Response) => res.json());
}
The problem might be related to CORS (Cross Origin Resource Sharing)
Thy to enable in your application -->
Enabling cors Rails5
Good luck