I have been trying for hours to fetch the data of some of my repositories but I keep getting this error
'POST https://api.github.com/graphql 401'
My Code
const githubData = {
token: "my token",
username: "mikechibuzor",
};
const body = {
query: `query {
user(login: "mikechibuzor"){
bio,
avatarUrl,
repositories(first: 20, orderBy: {field: CREATED_AT, direction: DESC}){
nodes{
name,
description,
forkCount,
languages(first: 100){
nodes{
name
}
}
}
}
}
}`,
};
const baseUrl = "https://api.github.com/graphql";
const headers = {
'Authorization': 'bearer ' + githubData.token,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
};
fetch(baseUrl, {
method: "POST",
Headers: headers,
body: JSON.stringify(body),
mode: "cors",
})
.then((response) => response.json())
.then((data) => console.log(data.data))
.catch((err) => console.log(JSON.stringify(err)));
What am i not doing right?
Maybe just a typo – try the following:
fetch(baseUrl, {
method: "POST",
// lowercase 'h' for headers
headers: headers,
body: JSON.stringify(body),
mode: "cors",
})
// ...
In case that still doesn't work check your scopes for your access token. GitHub gives you detailed control about what kind of actions you want to allow with a specific token and what not.
Getting data: { error: 'invalid_request', error_description: 'Missing grant type' } }
Content-Type is correct, not sure what is wrong
return axiosInstance({
method: 'post',
url: axiosInstance.defaults.baseURL + '/oauth/token',
data: {
"grant_type": "vapi_key",
key: api_key
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
Edit: This is called via NodeJS
This is an open issue about this matter. Try this solution, Which suggest stringifing the data (you can use qs package for it) :
import qs from 'qs';
return axiosInstance({
method: 'post',
url: axiosInstance.defaults.baseURL + '/oauth/token',
data: {
"grant_type": "vapi_key",
key: api_key
},
data: qs.stringify({
"grant_type": "vapi_key",
key: api_key
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
I have one task to fetch the data from iServer to SharePoint page using rest. I am getting the error:
'Failed to load resource: net::ERR_NAME_NOT_RESOLVED'.
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function () {
EventsCalenderfunc();
});
function EventsCalenderfunc() {
$.ajax
({
url: "https://{iserver URL}/_api/web/items",
type: 'GET',
data: JSON,
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": null
},
cache: false,
success: function (data) {
for (var i = 0; i < data.d.results.length; i++) {
var item = data.d.results[i];
console.log(item);
}
},
error: function (data) {
console.log('Something is wrong');
}
});
}
</script>
In console I am getting the output 'Something is wrong' and the error described above.
I have written an Axios POST request as recommended from the npm package documentation like:
var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data)
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
And it works, but now I have modified my backend API to accept headers.
Content-Type: 'application/json'
Authorization: 'JWT fefege...'
Now, this request works fine on Postman, but when writing an axios call, I follow this link and can't quite get it to work.
I am constantly getting 400 BAD Request error.
Here is my modified request:
axios.post(Helper.getUserAPI(), {
headers: {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
},
data
})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
When using Axios, in order to pass custom headers, supply an object containing the headers as the last argument
Modify your Axios request like:
const headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(Helper.getUserAPI(), data, {
headers: headers
})
.then((response) => {
dispatch({
type: FOUND_USER,
data: response.data[0]
})
})
.catch((error) => {
dispatch({
type: ERROR_FINDING_USER
})
})
Here is a full example of an axios.post request with custom headers
var postData = {
email: "test#test.com",
password: "password"
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
};
axios.post('http://<host>:<port>/<path>', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
To set headers in an Axios POST request, pass the third object to the axios.post() call.
const token = '..your token..'
axios.post(url, {
//...data
}, {
headers: {
'Authorization': `Basic ${token}`
}
})
To set headers in an Axios GET request, pass a second object to the axios.get() call.
const token = '..your token..'
axios.get(url, {
headers: {
'Authorization': `Basic ${token}`
}
})
const data = {
email: "me#me.com",
username: "me"
};
const options = {
headers: {
'Content-Type': 'application/json',
}
};
axios.post('http://path', data, options)
.then((res) => {
console.log("RESPONSE ==== : ", res);
})
.catch((err) => {
console.log("ERROR: ====", err);
})
All status codes above 400 will be caught in the Axios catch block.
Also, headers are optional for the post method in Axios
You can also use interceptors to pass the headers
It can save you a lot of code
axios.interceptors.request.use(config => {
if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
config.headers['Content-Type'] = 'application/json;charset=utf-8';
const accessToken = AuthService.getAccessToken();
if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;
return config;
});
Shubham's answer didn't work for me.
When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization.
The below example is working fine.
var headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(Helper.getUserAPI(), data, {"headers" : headers})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
We can pass headers as arguments,
onClickHandler = () => {
const data = new FormData();
for (var x = 0; x < this.state.selectedFile.length; x++) {
data.append("file", this.state.selectedFile[x]);
}
const options = {
headers: {
"Content-Type": "application/json",
},
};
axios
.post("http://localhost:8000/upload", data, options, {
onUploadProgress: (ProgressEvent) => {
this.setState({
loaded: (ProgressEvent.loaded / ProgressEvent.total) * 100,
});
},
})
.then((res) => {
// then print response status
console.log("upload success");
})
.catch((err) => {
// then print response status
console.log("upload fail with error: ", err);
});
};
axios.post can accept 3 arguments that the last argument can accept a config object that you can set header.
Sample code with your question:
var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data, {
headers: {Authorization: token && `Bearer ${ token }`}
})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
If you are using some property from vuejs prototype that can't be read on creation you can also define headers and write i.e.
storePropertyMaxSpeed(){
axios
.post(
"api/property",
{
property_name: "max_speed",
property_amount: this.newPropertyMaxSpeed,
},
{
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + this.$gate.token(),
},
}
)
.then(() => {
//this below peace of code isn't important
Event.$emit("dbPropertyChanged");
$("#addPropertyMaxSpeedModal").modal("hide");
Swal.fire({
position: "center",
type: "success",
title: "Nova brzina unešena u bazu",
showConfirmButton: false,
timer: 1500,
});
})
.catch(() => {
Swal.fire("Neuspješno!", "Nešto je pošlo do đavola", "warning");
});
};
Interceptors
I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined for the promise:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
i would like to delete item from list in SharePoint 2016. I use SharePoint REST API, but I cannot successfully delete item. This is error message (http code 400):
A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry.A 'StartObject' node was expected.
Here is my code:
$.ajax({
url: 'https://myshp.com/test/_api/web/lists(guid'e23e21c7-ab29-445e-87b8-2b20b721f79d')/items?$filter=ID eq '5'',
type: 'POST',
contentType: 'application/json;odata=verbose',
headers: {
"ACCEPT": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method-Override": "DELETE"
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
What is incorrect? Thanks
Please use below code: It works fine for me :
$.ajax({
url: "https://myshp.com/test/_api/web/lists(guid'e23e21c7-ab29-445e-87b8-2b20b721f79d')/items(5)",
type: 'POST',
contentType: 'application/json;odata=verbose',
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "DELETE"
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
})