Vue Resource - 401 (Unauthorized) - javascript

when I call the method "getUserData" I unfortunately get a 401 (Unauthorized)" error. But if call the URL "http://ppstemp.com/api/User/Profile" with GET and the same headers in Postman, it works!`
how i set my request headers??
this.$http.get('http://ppstemp.com/api/User/Profile',{params:{
n: ...
}} , {
headers: {
"Authorization": "bearer "+ localStorage.getItem('token') ,
"Accept": "application/json",
"cache-control": "no-cache"
}
}).then(
(response) => {
// Handle data returned
console.log(response.data);
},
//error callback
(err) => console.log(err));
}

Vue resource get method signature looks like -
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
You need to pass params along with the headers object.
this.$http.get('http://ppstemp.com/api/User/Profile', {
params: {
n: ...
},
headers: {
"Authorization": "bearer " + localStorage.getItem('token'),
"Accept": "application/json",
"cache-control": "no-cache"
}
}).then(
(response) => {
// Handle data returned
console.log(response.data);
},
//error callback
(err) => console.log(err));
}

Related

Why does my request return an ERR_BAD_REQUEST?

I am making a request from postman that returns the requested information without problem, additionally I did the test using curl and in the same way it returns the information successfully.But when doing it from axios it returns an ERR_BAD_REQUEST, the code is the following:
const axios = require('axios');
let payload = {
"payment_method": {
"type": "CARD",
"installments": 2,
"token": "tok_prod_some_token"
}
};
let config = {
method: 'post',
url: 'https://hereismyurl/v1/tokens/cards',
data:payload,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer pub_prod_some_public_key'
},
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
I can't understand what I'm sending wrong in my request

Get Reponse Code and JSON Response in Fetch

I have following Code to get the Response from the API. Now I want a response if the data are successfully send to the server. My first idea was to do it with the response code. If it is 200 it is successfull. The other idea is, to make it with a try catch statement.
public async daten_eintragen(): Promise<void> {
// try {
const headers = {
"Access-Control-Allow-Origin": "localhost",
"Access-Control-Allow-Methods": "OPTIONS, GET, POST, PUT, PATCH, DELETE",
};
const jsondata = {
proasdftName: "tfghtdsddskt",
pauctasdfsion: "this.csdfgudfghrrentItemVersio",
cosdfasdftName: "mardfddsdfgfdfbvdfdasdfumfghjann",
vdon: "this.currentItesdfghdfmVersion",
vedor: "this.currentsdfgItemVendor",
lde: "this.currentsdfdfgItemFrdgfhamework",
proepage: "this.csdfgurrentItedfghmHomepage",
nType: "this.cursdfgrentItedfghmIntegration",
upe: "this.currentItsdfgfdghemUsage",
sL: "this.currentItemSsdfgourcfgheCodeAnpassungen",
};
console.log(this.currentItemName);
fetch(this.appConf.apiBaseUrl + "compon", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(jsondata),
}).then(async (response) => {
// get json response here
let data = await response.json();
console.log(data);
});
}
Getting the response from the server it was successful.
Looking at the response properties you can simply check response.ok. Something like this:
fetch(this.appConf.apiBaseUrl + "compon", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(jsondata),
}).then(async (response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
console.log("request was successfull. Proceeding with extracting data");
// get json response here
let data = await response.json();
console.log("data", data);
}).catch(e => {
console.log('An error occurred', e);
});

Axios PUT got Unhandled Runtime Error Error: Request failed with status code 500

I have axios PUT method in API and it's got Unhandled Runtime Error
Here's Image of an Error
Error: Request failed with status code 500
update: async (article, pid, token) => {
const { data, status } = await axios.put(
`${apiPath}/articles/${pid}`,
JSON.stringify({ article }),
{
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${encodeURIComponent(token)}`,
},
}
)
return {
data,
status,
}
},
But for POST method it working real fine, so I'm in very deep confusion
create: async (article, token) => {
const { data, status } = await axios.post(
`${apiPath}/articles`,
JSON.stringify({ article }),
{
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${encodeURIComponent(token)}`,
},
}
)
return {
data,
status,
}
},
}

Getting 400 Bad Request on axios post call

I'm using a url shortner API to test connecting to a API and I keep getting a 400 BadRequest. I've read through a dozen posts here and tried all suggestions and still nothing will work. I don't know what I'm doing wrong.
Function
var axios = require('axios');
module.exports = function (callback, data) {
let url = 'https://cleanuri.com/api/v1/shorten';
let axiosConfig = {
"headers": {
'Content-Type': 'application/json;charset=UTF-8'
}
};
let longUrl = { "url" : data };
axios(url, {
method: "post",
params: {
"url" : data
},
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
})
.then(function (response) {
callback(null, response.data);
}).catch(function (err) {
console.log("error: " + err.response);
callback(err, null);
});
I've also tried this and got same error
axios.post(url, JSON.stringify(longUrl), axiosConfig)
.then(function (response) {
callback(null, response.data);
}).catch(function (err) {
console.log("error: " + err.response);
callback(err, null);
});
To send data as body use data field on request options
const payload = { ... }
axios({ ..., data: payload })
params field is used to send query string within url
I have read your api docs https://cleanuri.com/docs.
That requiring your payload send as body, so use data field
Here the snippet:
let payload = { "url" : data };
axios(url, {
method: "post",
data: payload,
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
})
Edit:
400 Bad Request is indicating your request is invalid (by server)

RxJS Ajax how to get response cookie

When I make an RxJS Ajax call request I set the headers of request, but how can i get Cookie of RxJS Ajax Response?
import { ajax } from 'rxjs/ajax';
ajax({
url: "some url",
body: {
parameter1: "abc",
parameter2: "def"
},
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache"
},
method: 'POST',
responseType: 'json'
})
.subscribe(
payLoad => {
console.log(payLoad);
console.log(payLoad.headers);
},
error => console.log(error),
() => console.log( 'done' )
);
You can set withCredentials: true to set appropriate XHR option so that cookies & headers will be treated differently.
And then, after request is done, access cookie using document.cookie or some other library
something like:
ajax("https://some-url").subscribe(
res => {
console.log(document.cookie);
}
);

Categories

Resources