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

Postman请求问题:Form Data可发送,Raw JSON失败(Angular5+Drupal8)

Hey there! I’ve run into similar issues with Drupal 8 and Angular in the past, so let’s walk through why your Raw JSON request is failing when Form Data works, and how to fix it step by step.

Why This Happens

There are a few common culprits here:

  • Mismatched Content-Type Headers: Form Data uses either multipart/form-data or application/x-www-form-urlencoded by default, while Raw JSON requires application/json. Drupal 8’s REST endpoints won’t process JSON requests unless this header is set correctly.
  • Missing CSRF Token: Drupal 8 requires a CSRF token for most POST/PUT/DELETE requests. Form Data requests might be handling this implicitly (if you’re using a session cookie), but Raw JSON requests need to explicitly include the token.
  • Incorrect JSON Structure: Drupal 8 expects entity fields to be formatted as arrays (even for single values), which is easy to miss when converting from Form Data’s key-value pairs.
Step-by-Step Fixes

1. Properly Configure Angular Requests

First, you need to fetch Drupal’s CSRF token and include it, along with the correct Content-Type header, in your POST request.

Fetch the CSRF Token

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

constructor(private http: HttpClient) {}

private getCsrfToken(): Observable<string> {
  // Drupal's dedicated endpoint for retrieving CSRF tokens
  return this.http.get('/rest/session/token', { responseType: 'text' });
}

Send the Raw JSON Request

sendDataToDrupal(data: any): void {
  this.getCsrfToken().subscribe(token => {
    const requestHeaders = {
      'Content-Type': 'application/json',
      'X-CSRF-Token': token,
      'Accept': 'application/json' // Ensure we accept JSON responses from Drupal
    };

    // Format data to match Drupal's entity field structure
    const formattedData = {
      title: [data.title], // Single values must be wrapped in arrays
      body: [{ 
        value: data.body, 
        format: 'basic_html' // Match your Drupal text format
      }]
    };

    this.http.post('/your-drupal-rest-endpoint', formattedData, { headers: requestHeaders })
      .subscribe(
        response => console.log('Request succeeded:', response),
        error => console.error('Request failed:', error)
      );
  });
}

2. Verify Drupal 8 REST Configuration

  • Enable JSON Request Format: Go to your Drupal admin panel → Configuration > Web services > REST. Edit the resource you’re targeting, and make sure application/json is checked under Accepted request formats.
  • Check Permissions: Ensure your user role has the necessary permissions: access rest resource, plus entity-specific permissions like create node (if you’re creating content) or update entity (if editing).

3. Match the JSON Structure to Drupal’s Expectations

This is the most common pitfall! For example:

  • If your Form Data had a title field with value "Test Post", the equivalent JSON for Drupal needs to be:
    {
      "title": ["Test Post"]
    }
    
  • For complex fields like body, you need an object inside an array (matching Drupal’s field structure):
    {
      "body": [{"value": "My content text", "format": "basic_html"}]
    }
    

4. Debug the Request Differences

Use your browser’s DevTools (Network tab) to compare your Angular request with the working Postman Raw JSON request. Check:

  • Is the Content-Type header set to application/json?
  • Is the X-CSRF-Token present and valid?
  • Does the JSON body match exactly what worked in Postman?
  • Check Drupal’s logs (Reports > Recent log messages) for detailed error messages—this will often tell you exactly what’s wrong (e.g., "Missing required field title" or "Invalid field format").

内容的提问来源于stack exchange,提问作者ValRob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:10:16