Angular 5调用Nutritionix API获取营养数据时遇400错误求助
Fixing the 400 Bad Request Error with Nutritionix API in Angular 5
Hey there, let's break down why you're hitting that 400 error and how to fix it quickly.
What's the Root Cause?
The error message spells it out clearly: child "query" fails because ["query" is required]. The Nutritionix natural/nutrients endpoint mandates a query field in your request body—this is where you specify the food you want nutrition data for (like "1 medium apple" or "2 slices of whole-grain bread"). Your current request isn't sending this required parameter, which is why the API is rejecting it with a bad request.
Corrected Service Code
I'll fill in the missing parts of your code to create a working example that properly includes the required query field:
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; @Injectable() export class NutritionService { private apiEndpoint = 'https://trackapi.nutritionix.com/v2/natural/nutrients'; // Set up authentication headers (replace with your actual Nutritionix credentials) private requestHeaders = new HttpHeaders({ 'Content-Type': 'application/json', 'x-app-id': 'YOUR_NUTRITIONIX_APP_ID', 'x-app-key': 'YOUR_NUTRITIONIX_APP_KEY' }); constructor(private http: HttpClient) { } fetchNutritionData(foodQuery: string): Observable<any> { // Critical: include the required "query" in the request body const requestBody = { query: foodQuery }; // Use POST (this endpoint only accepts POST requests, not GET) return this.http.post<any>(this.apiEndpoint, requestBody, { headers: this.requestHeaders }); } }
Key Checks to Ensure Success
- Replace Credentials: Swap
YOUR_NUTRITIONIX_APP_IDandYOUR_NUTRITIONIX_APP_KEYwith the actual values from your Nutritionix developer account. - Call the Service Properly: In your component, pass a valid food query string when invoking the service:
// Example component usage import { Component } from '@angular/core'; import { NutritionService } from './nutrition.service'; @Component({ selector: 'app-food-search', template: '<button (click)="getAppleNutrition()">Get Apple Nutrition</button>' }) export class FoodSearchComponent { constructor(private nutritionService: NutritionService) { } getAppleNutrition() { this.nutritionService.fetchNutritionData("1 medium apple") .subscribe( data => console.log('Nutrition Results:', data), error => console.error('Request Error:', error) ); } } - Use POST, Not GET: The
natural/nutrientsendpoint only accepts POST requests—if you were usinghttp.get()before, that's another reason for the error. - Validate Headers: Make sure
Content-Type: application/jsonis set so the API can correctly parse your request body.
内容的提问来源于stack exchange,提问作者Ivan Fan Tang
相关产品推荐
相关产品推荐

