You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_ID and YOUR_NUTRITIONIX_APP_KEY with 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/nutrients endpoint only accepts POST requests—if you were using http.get() before, that's another reason for the error.
  • Validate Headers: Make sure Content-Type: application/json is set so the API can correctly parse your request body.

内容的提问来源于stack exchange,提问作者Ivan Fan Tang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:56:18