Cannot convert data to json in angular 13 Content type 'text/plain;charset=UTF-8' not supported] after sending data from angular to .Net core Web Api - asp.net-core-webapi

I am trying to connect a WebAPI build using .Net core 5
Web API: method
// POST api/<BusController>
//[EnableCors("AllowAllHeaders")]
[HttpPost]
public JsonResult Post([FromBody]BusRequest busRequest)
{
var result = "Response Text";
return new JsonResult(result);
//return result;
}
Angular 13 Code
const busRequest = {
"StartDate" : "02/15/2022",
"EndDate": "02/17/2022",
"BusNo" :null
};
**Approach 1:**
const header = new HttpHeaders();
header.set('Content-Type', 'application/x-www-form-urlencoded;application/json; charset=utf-8');
header.set('Accept','application/json');
const options = {headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'}),
observe: 'response' as 'response',
responseType: 'json' as 'json',
body: busRequest};
this.http.request('post', 'http://localhost:55047/api/bus', options).subscribe();
**Approach 2:**
let headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;application/json; charset=utf-8', 'Accept': 'application/json'});
this.http.post('http://localhost:55047/api/bus', JSON.stringify(Request), {headers: headers}).subscribe(data => {
console.log(data);
});
But nothing works.
Response is:
tatus: 415
title: "Unsupported Media Type"
traceId: "00-403257012c151a469a0e24b083d61d62-56ac63710daf8c45-00"
type: "https://tools.ietf.org/html/rfc7231#section-6.5.13"
Did anyone faced the similar problem?

Related

getting error responses from nft.storage's /store API endpoint using fetch

let formData = new FormData();
formData.append("name",name);
formData.append("description",description);
formData.append("image", image);
fetch("https://api.nft.storage/store",{
method: "POST",
body: formData,
headers: {
'Authorization': 'Bearer '+process.env.TEST_API_KEY,
}
}).then(response => response.json())
.then((json)=>{
console.log(json)
})
This is what I've been trying to do but keep getting error as a response. Errors are usually invalid-file or something to do with content-type.
https://nft.storage/api-docs/ - This is the api documentation. If theres any example for the same, it'll be really helpful. Thanks!
Long time since question... just for any one wondering:
The api endpoint receives 1 parameter called meta which is a json_encoded representation of the fields, any falsy value like image: undefined, will be replaced with an extra field you must include, with the binary representation of the field... here is an example:
let params = {
name: 'name of the nft',
image: undefined,
description: 'description of the nft'
}
let formData = new FormData();
formData.append("meta",JSON.stringify(params));
formData.append("image",new File([ someBinaryImageData ], 'nft.png', { type: 'image/png' });
fetch("https://api.nft.storage/store",{
method: "POST",
body: formData,
headers: {
'Authorization': 'Bearer '+process.env.TEST_API_KEY,
}
})
.then(response => response.json())
.then((json)=>{
console.log(json);
})

Send a request to Asp.net WebService using Angular

I executed a WebService using Postman and it's executed correctly. And now i want to send a request to the WebService using Angular
Here is the Asp.net Web Service
This is the code for my WebService
public class Temperature : System.Web.Services.WebService
{
[WebMethod]
public double Farenheit(double celsius)
{
return (celsius * 9) / 5 + 32;
}
[WebMethod]
public double Celsius(double fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}
}
And this is the screenshot on how i send a request using PostMan and it's working as expected
Screenshot for Calling the WebService using Postman
Here is the code for the Angular
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'text/xml',
})
};
this.http.post('https://localhost:44389/Temperature.asmx/Celsius', '50', httpOptions)
.subscribe(res => {
console.log('Data: ' + res);
})
And this is the error I'm receiving
Error
"System.InvalidOperationException: Request format is invalid: text/xml.
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
"
Message
Http failure response for https://localhost:44389/Temperature.asmx/Celsius: 500 OK
Name
"HttpErrorResponse"
Change your 'Content-Type': 'text/xml' to 'Content-Type': 'application/json'
try this :
import { HttpHeaders } from '#angular/common/http';
setHttpHeader() {
const headers = new HttpHeaders().set('Accept', 'application/json').set('Content-Type', 'application/json');
let options = { headers: headers };
return options;
}
this.http.post('https://localhost:44389/Temperature.asmx/Celsius', '50', this.setHttpHeader())
.subscribe(res => {
console.log('Data: ' + res);
})

Rails API not receiving fetch POST data from body

I have a route in Rails API '/api/pay'. My client side post request successfully hits the controller action, however nothing I send in the body: JSON.stringify('...') gets through to the back-end. Other post requests I have made work just fine with the same format.
export const payForItem = (payData) => {
return dispatch => {
dispatch(payForItemStart());
// ?userID=${data.userID}&adID=${data.adID}&price=${data.price}
const data = {userID: payData.userID, adID: payData.adID, price: payData.price}
fetch(`/api/pay`, {
method: 'POST',
header: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
})
Here is what payData looks like.
Rails Api back-end params
Probably you've got typo in headers section. Should be plural headerS with s:
headers: {
"Content-Type": "application/json"
}

Angular 5 - HTTP post

I have a backend interface which I invoke with my Angular 1.3 application without problems. With my Angular 5 application I get an HTTP 403 (Forbidden)
I faced the request parameters in an picture (Angular 1.3 at the left side, Angular 5 at the right side):
My Angular 5 code looks like this:
createDate(calendarEvent: CalendarEvent) {
let serialDates = false;
let calendarEventSerialDateType = 'NO_SERIAL_DATE';
let serialEndDate = this.utilService.convertDateToDateString(new Date());
let url: string = environment.apiEndpoint + 'calendarevents/calendarevent/' + serialDates + '/' + calendarEventSerialDateType + '/' + serialEndDate + '/';
let headers = new Headers({ 'Content-Type': 'application/json', 'X-AUTH-TOKEN': this.authService.getToken()});
let options = new RequestOptions({ headers: headers });
return this.http.post(url, calendarEvent, options).map(res => res.json()).subscribe(res => console.log(res));
}
I have e.g. no idea why X-AUTH-TOKEN is not set with Angular 5 because I set it in the headers object with
let headers = new Headers({ 'Content-Type': 'application/json', 'X-AUTH-TOKEN': this.authService.getToken()});
and why OPTIONS is mentioned at Request Method with Angular 5 instead of POST like with angular 1.3.
Does anyone have any idea what I am doing wrong?
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(url, calendarEvent, Options).map(res => res.json()).subscribe(res => console.log(res));
OPTIONS request is considered as a pre-flight request, which is sent before the actual request to check the existence of method.
If the request sent is a valid one, it will call the valid method.
And regarding the request header, you can use the one in the above answer.
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
For Angular5,
import { HttpClient, HttpHeaders } from '#angular/common/http';
const headers = new HttpHeaders().set('X-AUTH-TOKEN', this.authService.getToken());
By default, 'Content-Type': 'application/json'
Stop using map.
Subscribe the response and store it to Observable for further access.
Example:
createDate(calendarEvent: CalendarEvent) {
let serialDates = false;
let calendarEventSerialDateType = 'NO_SERIAL_DATE';
let serialEndDate = this.utilService.convertDateToDateString(new Date());
let url: string = environment.apiEndpoint + 'calendarevents/calendarevent/' + serialDates + '/' + calendarEventSerialDateType + '/' + serialEndDate + '/';
let headers = new HttpHeaders().set('X-AUTH-TOKEN', this.authService.getToken());
return this.http.post(url, calendarEvent, {headers: headers}).subscribe(res => console.log(res));
}

http post request with response in angular2 Nativescript

i am new to angular2 native script programming.. i need to post data to a particular url from my app. when i try to post data then get a message on console Response with status: 200 for URL: null. whats the meaning of this message.? and what should i do for successfull post request..?
//my code
let headers = new Headers({ "Content-Type": "application/json" });
let options = new RequestOptions({ headers: headers });
let body =
{
"firstName": "boby",
"lastName": "samuels",
"Location": "UK"
};
this.http.post("http://example.com", JSON.stringify(body), options)
.subscribe(result =>
{
console.log("response : "+result);
}, error =>
{
console.dir(error);
});
please help me out.

Resources