POST请求Angular 2 Drupal 8上的错误422

时间:2016-12-02 12:06:22

标签: javascript json angular typescript drupal

我正在尝试向Drupal网站发送POST请求(创建内容类型测试的新节点),但我收到错误422(不可处理的实体)

这是我在Angular的服务:

createBlog(blog: Blog): Observable<any>{
  let url = this.API_URL + "entity/node";
   blog._links = {type : { href: 'http://example.co.uk/rest/type/node/test' } };
  return this.http.post(url, blog,  {headers:this.headers}).map(res => res.json()).catch(err => {
 console.log(blog)
    return Observable.throw(err.json);
  });
}

这是我在表单提交后在控制台中获得的内容:

enter image description here

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

在通过http发布之前使用JSON.stringify(data)方法。

return this.http.post(url, JSON.stringify(blog), headers).map((res: Response) => res.json());

修改

Aso使用如下标题。

import { Headers, Response, RequestOptions} from "@angular/http"; 
...

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(blog);
return this.http.post(url, body, options).map((res: Response) => res.json());

答案 1 :(得分:0)

对于此功能:

addTask (task: Task): Observable<Task> {

  const url = `${this.mainUrl}/entity/node`;  

  const postReturn = this.http.post(url, task, httpHaljson);

  return postReturn
}

这就是我如何声明api和标题:

  mainUrl : 'http://drupal.dd:8083',
  httpHaljson : {
                  headers: new HttpHeaders({ 
                  "X-CSRF-Token": "Qfnczb1SUnvOAsEy0A_xuGp_rkompgO2oTkCBOSEItM",
                  "Authorization": "Basic Qfnczb1SUnvOAsEy0A_xuGp_rkompgO2oTkCBOSEItM", // encoded user/pass - this is admin/123qwe
                  // "Content-Type": "application/json"
                  "Content-Type": "application/hal+json"
                  })
                }

而最重要的任务必须做这样的事情:

{
  "_links": {
    "type": {
      "href": "http://drupal.dd:8083/rest/type/node/task"
    }
  },
  "title": {
    "value": "I am a new task"
  },
  "type": {
    "target_id": "task"
  }
}

为此,在从表格中回复一些数据后,我这样做:

   onSubmit(name: string, body:string): void {
   let task: any = {
       _links: null,
       type: null,
       title: null,
       body: null     
    };

    task._links = {type: {"href": "http://drupal.dd:8083/rest/type/node/task"} };
    task.type = {target_id: "task"};
    task.title = {value: name};
    task.body = { "": body};

      this.taskService.addTask(task)
        .subscribe(task => {
          this.tasks.push(task);
          // console.log(JSON.stringify(task));

          this.getTasks();
        });
    }

看看我的:console.log(JSON.stringify(task));是关键,有了这个,你可以看到你有多远来创造drupal想要的东西。

看这个guide