0

I am trying to post some data to a repo on GitLab using the JavaScript Fetch API and it's not working. Here is my JavaScript code:

const url = "https://gitlab.com/api/v4/projects/XXXXXXXX/repository/files/first-post%2Emd";

const request = new Request( url );

fetch( request, {
    method: 'POST',
    headers: { "private-token": "xxxxxxxxxxxxxxxxxxxx", 'Content-Type': 'application/json' },
    data: { "branch": "master", "author_email": "[email protected]", "author_name": "Firstname Lastname", "content": "some content", "commit_message": "create a new file"}

} ).then( ( response ) => {

    if ( response.ok ) {

        return response.json();

    } else {

        return Promise.reject( response );
    }

} ).then( ( data ) => {

    document.write (JSON.stringify( data ) );

} ).catch( ( err ) => {

    console.warn( 'Something went wrong.', err );

} );

What is wrong here?

The response I get in the console:

PUT https://gitlab.com/api/v4/projects/13175347/repository/files/first-post.md?ref=master 400 (Bad Request) fetch-gitlab-post-0-00.html:34 Something went wrong. Response {type: "cors", url: "https://gitlab.com/api/v4/projects/13175347/repository/files/first-post.md?ref=master", redirected: false, status: 400, ok: false, …} (anonymous) @ fetch-gitlab-post-0-00.html:34 Promise.catch (async) (anonymous) @ fetch-gitlab-post-0-00.html:32

Here is the curl command that is working that I am trying to follow:

curl --request PUT \
--header "PRIVATE-TOKEN: xxxxxxxxxxxxxxxxxxxx" \
--header "Content-Type: application/json" \
--data '{"branch": "master", "author_email": "[email protected]", 
"author_name": "Firstname Lastname", "content": "some content \nabc 123\ntra 
la\nhello world", "commit_message": "create a new file"}' \
https://gitlab.com/api/v4/projects/XXXXXXX/repository/files/project2%2Emd
6
  • 1
    most probably due to 2 headers header: { "private-token": "xxxxxxxxxxxxxxxxxxxx", 'Content-Type': 'application/json' } Commented Sep 22, 2019 at 4:34
  • source edited to a single headers item, but the same errors occur Commented Sep 24, 2019 at 0:38
  • 2
    data is not part of the Request API. You probably meant body and you probably also meant to run it through JSON.stringify() Commented Sep 24, 2019 at 0:39
  • 1
    Please see the linked duplicate. You want fetch(url, { method: 'PUT', headers: { 'private-token': 'xxx', 'content-type': 'application/json' }, body: JSON.stringify({ branch: 'master', ... }) }) Commented Sep 24, 2019 at 2:23
  • @Phil Thanks. I tried changing 'data' to 'body. And I am looking at developer.mozilla.org/en-US/docs/Web/API/Request but I am not there yet. I did add a working curl command to the question. the curl is from: docs.gitlab.com/ee/api/…. Commented Sep 24, 2019 at 2:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.