Angular post request body is null when received by Spring API - Stack Overflow
I am submitting a request from a simple Angular app to test a Spring endpoint I have made. The same JSON is processed successfully when I submit it through Postman, so I suspect that there is something wrong on the Angular side. Here is what the front and backend look like:
tft-calculator.service.ts
:
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class TftCalculatorService {
apiUrl = 'http://localhost:8080'
constructor(private http: HttpClient) { }
calculateChanceOfHitting(){
let data: object;
data = {"name":"Mordekaiser",
"targetCount":3,
"currentUnits":0,
"sameUnitOnOtherBoards":0,
"currentLevel":8,
"currentGold": 130,
"prismaticTicket": false};
let params = new HttpParams().set("requestData", JSON.stringify(data));
console.log(params);
let headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');;
return this.http.post<any[]>(`${this.apiUrl}/calculateChanceOfHitting`,
{params: data,
headers: headers});
}
}
TFTController.java
:
package com.example.gamingcalculator;
import com.example.gamingcalculator.pojo.CalculatorParams;
import com.example.gamingcalculator.pojo.Unit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@CrossOrigin(origins = "*")
public class TFTController {
@Autowired
TFTService tftService;
@GetMapping("/calculateGoldNeeded")
@ResponseBody
public int calculateGoldNeeded(@RequestBody CalculatorParams params) {
return tftService.calculateGoldNeeded(params.getName(),
params.getTargetCount(),
params.getCurrentUnits(),
params.getSameUnitOnOtherBoards(),
params.getCurrentLevel());
}
@PostMapping("/calculateChanceOfHitting")
@ResponseBody
public double calculateChanceOfHitting(@RequestBody CalculatorParams params) {
return tftService.calculateChanceOfHitting(params.getName(),
params.getTargetCount(),
params.getCurrentUnits(),
params.getSameUnitOnOtherBoards(),
params.getCurrentLevel(),
params.getCurrentGold(),
params.isPrismaticTicket());
}
}
Here is what the HTTP request looks like from the front end
And here are the parameters from a debug line immediately after the controller is hit
I have tried changing the formatting of the JSON, but I suspect that there is something particular in the Angular that I'm missing.
I am submitting a request from a simple Angular app to test a Spring endpoint I have made. The same JSON is processed successfully when I submit it through Postman, so I suspect that there is something wrong on the Angular side. Here is what the front and backend look like:
tft-calculator.service.ts
:
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class TftCalculatorService {
apiUrl = 'http://localhost:8080'
constructor(private http: HttpClient) { }
calculateChanceOfHitting(){
let data: object;
data = {"name":"Mordekaiser",
"targetCount":3,
"currentUnits":0,
"sameUnitOnOtherBoards":0,
"currentLevel":8,
"currentGold": 130,
"prismaticTicket": false};
let params = new HttpParams().set("requestData", JSON.stringify(data));
console.log(params);
let headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');;
return this.http.post<any[]>(`${this.apiUrl}/calculateChanceOfHitting`,
{params: data,
headers: headers});
}
}
TFTController.java
:
package com.example.gamingcalculator;
import com.example.gamingcalculator.pojo.CalculatorParams;
import com.example.gamingcalculator.pojo.Unit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@CrossOrigin(origins = "*")
public class TFTController {
@Autowired
TFTService tftService;
@GetMapping("/calculateGoldNeeded")
@ResponseBody
public int calculateGoldNeeded(@RequestBody CalculatorParams params) {
return tftService.calculateGoldNeeded(params.getName(),
params.getTargetCount(),
params.getCurrentUnits(),
params.getSameUnitOnOtherBoards(),
params.getCurrentLevel());
}
@PostMapping("/calculateChanceOfHitting")
@ResponseBody
public double calculateChanceOfHitting(@RequestBody CalculatorParams params) {
return tftService.calculateChanceOfHitting(params.getName(),
params.getTargetCount(),
params.getCurrentUnits(),
params.getSameUnitOnOtherBoards(),
params.getCurrentLevel(),
params.getCurrentGold(),
params.isPrismaticTicket());
}
}
Here is what the HTTP request looks like from the front end
And here are the parameters from a debug line immediately after the controller is hit
I have tried changing the formatting of the JSON, but I suspect that there is something particular in the Angular that I'm missing.
Share Improve this question edited yesterday jonrsharpe 122k30 gold badges263 silver badges469 bronze badges asked yesterday alexander acevedoalexander acevedo 9 New contributor alexander acevedo is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 2 |1 Answer
Reset to default 0Couple of changes
- Send object as body instead of params. Params is only for query params
- You don't need to set headers as JSON, because by default it's JSON
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders, HttpParams} from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class TftCalculatorService {
apiUrl = 'http://localhost:8080'
constructor(private http: HttpClient) { }
calculateChanceOfHitting(){
const data = {"name":"Mordekaiser",
"targetCount":3,
"currentUnits":0,
"sameUnitOnOtherBoards":0,
"currentLevel":8,
"currentGold": 130,
"prismaticTicket": false};
return this.http.post<any[]>(`${this.apiUrl}/calculateChanceOfHitting`,data);
}
}
- 下个月Win7正式“退休”,数据显示国内近60%电脑用户仍在使用
- 苹果安卓交锋:开放做强生态链
- TGUI Using raylib backend with cmake - Stack Overflow
- typescript - tag a href download filename nextjs - Stack Overflow
- maven - How can I get the dependencies about the master code of mule? - Stack Overflow
- tensorflow - How can I use training data into my custom metric? - Stack Overflow
- swiftui - Previewing SwiftData Records in Xcode Previews - Stack Overflow
- asynchronous - Parallelization by threads vs Parallelization by processes on backend - Stack Overflow
- x86 - how does internal functions of kernel resolve after paging? - Stack Overflow
- kotlin - How to implement "Swipe to Go Back" in iOS with Compose Multiplatform (1.7.3) - Stack Overflow
- terraform - Restrict Savings Plan creation outside specified subscription in Mgmt group via Azure Policy - Stack Overflow
- asp.net - Delete Button does not delete in C# Webforms - Stack Overflow
- eclipse - Floodlight debug Exception in thread "main" java.lang.Error - Stack Overflow
- keyboard - Issue with java.awt.Robot KeyEvent for Special Characters (e.g., : and ) - Stack Overflow
- How to Use GraalVM to Execute JavaScript Code Making REST Calls Using Java? - Stack Overflow
- c++ - Pointer of an object which has static storage as template non-type parameter, Clang and GCC agrees, MSVC doesn't -
- tsconfig - Is there a typescript compiler option that prevents implicit widening from readonly properties to readwrite? - Stack
body
andoptions
: angular.dev/guide/http/making-requests#mutating-server-state. Also, in the options,params
is for URL (search/query) parameters, not the request body: angular.dev/guide/http/making-requests#setting-url-parameters. Look at what the network tab is showing - the "headers" are in the body. – jonrsharpe Commented yesterday{...data}
in your second param. – rakesh shrestha Commented yesterday