0

Below is my code, every time I am getting 400, I am trying spHttpClient to create a column in a SP List.. Please suggest

SPFx Code

    let listTitle = document.getElementById("txtListTitle")["value"]; //TestList
    let columnName = document.getElementById("txtColumnName")["value"]; //
    let columnType = $("#ddlColumnType :selected").val();//2 for Single Line of Text
    columnType = parseInt(columnType.toString());
    let fieldType = $("#ddlColumnType :selected").attr("name")//"SP.Field"
    let SelectedText = $("#ddlColumnType :selected").text();//"Single Line Of Text"

    const fieldQry: string = this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('" + listTitle + "')/fields";

    const objectData: any = {
      '__metadata': { 'type': fieldType },
      'FieldTypeKind': columnType,
      'Title': columnName
    }
    const fieldsClientOptions: ISPHttpClientOptions = {
      "body": JSON.stringify(objectData)
    }
    this.context.spHttpClient.post(fieldQry, SPHttpClient.configurations.v1, fieldsClientOptions).then(
      (responseColumn: SPHttpClientResponse) => {
        if (responseColumn.status == 201) {
          alert(columnName + " column created!!")
        }
      })
3
  • Instead of "body": JSON.stringify(objectData), try sending it as "data": JSON.stringify(objectData) and check – Gautam Sheth Jul 28 '20 at 12:03
  • Type '{ data: string; }' is not assignable to type 'ISPHttpClientOptions'. Object literal may only specify known properties, and '"data"' does not exist in type 'ISPHttpClientOptions'. – Tezz Chaudhary Jul 28 '20 at 12:09
  • My bad, figured out the issue. – Gautam Sheth Jul 28 '20 at 12:15
0

You need to modify the code as below, we are adding slightly modified headers for SPFx as it uses OData v4 behind the scenes:

const headers = new Headers();
headers.append("Accept", "application/json;odata.metadata=full");
headers.append("Content-type", "application/json;odata.metadata=full");

const fieldsClientOptions: ISPHttpClientOptions = {
    headers: headers,
    body: `{ "@odata.type": "#SP.Field", "Title": columnName, "FieldTypeKind": columnType}`
};
1
  • 1
    Yes! It worked, but I didn't used the headers – Tezz Chaudhary Jul 28 '20 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.