求助:如何让POST请求以指定平级对象格式提交用户数据
Looks like the issue is super straightforward—you're wrapping your user data in an extra user object when making the POST request, which is why your payload ends up nested. Let's fix that!
What's Causing the Problem
In your POST call, you're using {user} as the request body. This is ES6 shorthand for {user: user}, which wraps your entire user dataset inside a top-level user key. That's exactly why your server receives the nested structure you don't want.
Corrected Code
Here's the fixed version of your code, with redundant FormData code removed (since it wasn't being used in the actual request) and the key change to eliminate the nested object:
constructor(private http: Http, private htp: HttpClient) { let user = { birthdate: '', email: 'jo@joe.com', firstname: 'jo', lastname: 'david', phone: '012345678', sex: 'male', identifier: '43425', username: 'joe', password: 'Kdsdsdsddew32', country: 'sa', affiliate: '3232' }; const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'}); // 👉直接传递user对象,而非包裹在{user}里 this.htp.post('http://192.168.66:323/test', user, {headers}).subscribe(data => { this.data = JSON.stringify(data); }); }
What This Changes
After this fix, your POST payload will match exactly the format you expected:
{"birthdate":"","email":"jo@joe.com","firstname":"jo","lastname":"david","phone":"012345678","sex":"male","identifier":"43425","username":"joe","password":"Kdsdsdsddew32","country":"sa","affiliate":"3232"}
Also, I removed the leading space in your request URL (' http://...' → 'http://...') to avoid any potential request routing issues.
内容的提问来源于stack exchange,提问作者joem

