Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HttpClient make GET request with JSON in the body

I am working on an Angular client application and a ASP.NET Core Web API backend, and I'm running into a problem trying to get a call to work from Angular that seems to work fine from Postman.

Typescript code:

exportScript(commands: ScriptCommand[]) {
    this.http.post(this.baseUrl + 'api/ScriptCommands/GenerateScript', JSON.stringify(this.scriptCommands)).subscribe();
}

C# API call:

[HttpGet]
[Route("api/ScriptCommands/GenerateScript")]
public IActionResult GenerateScript([FromBody]List<ScriptCommandViewModel> commands)
{
    var mappedCommands = MapCommands(commands);
    var stream = ProcessCommands(mappedCommands);
    return File(stream, "application/xml", "generatedScript.xml");
}

When I use the Angular call, I get a 400 Bad Request back, but if I copy the JSON-stringified scriptCommand list into the body of a Postman request, it works just fine.

Thanks for the help, everyone!

UPDATE: Changed Typescript code - I still get an HTTP 400 Bad Request response, but my Network tab in Chrome shows this in the Request headers - is the content-type being 'text/plain' the issue?

Accept: application/json, text/plain, */*
Content-Type: text/plain
Origin: http://localhost:4200
Referer: http://localhost:4200/createScript
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36
like image 645
Riddari Avatar asked Jul 15 '26 22:07

Riddari


1 Answers

GET request send data by appending it in request url, so if you have a json body like {"page":1,"search":"new products"}. To send this data in a GET request you can use below code.

get(path: string, params: any) {
    return this._http.get(this._baseUrl + path, { params: params })
        .pipe(timeout(CONST.API_TIMEOUT));
}

This will is create request URL like (can be verified in console in network tab)

http://localhost:5003/api/auth/test?page=1&search=new products
like image 180
kode Avatar answered Jul 18 '26 12:07

kode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!