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": "author@example.com", "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": "author@example.com",
"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