getting problem performing a post request to an external API - node.js

I'm using axios to perform get and post requests to an external api,
i have finally succeed to achieve get request (problem with the ssl certificate, i avoid it by adding this :
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
now i would like to post the api,
to get the request working in postman, i put in
headers content-type : application/json
and in the body : {}
like here
when trying with a google chrome extention, to make it work, i put nothing in the headers but in params, i select customer : application/json and i put inside this {} instead of the default choice which is x-www-form-urlencoded;charset=UTF-8
chrome extention
in my javascript app i tried this
var url = https://10.11.31.100:9440/api/nutanix/v3/images/list;
axios({
method:'post',
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
url,
auth: {
username: '******',
password: '********'
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
params: {},
data: {}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I get this problem :
TypeError : UTF-8 is not a function

Specifically with regards to the Nutanix v3 REST API - this is probably because the POST request above doesn't have an appropriate JSON payload i.e. the "data" parameter is empty.
When sending Nutanix v3 API POST requests, specifically to "list" entities, you'll need to specify the "kind" of entity being listed. In your example, the JSON payload below will work.
{"kind":"image"}
See here: https://nutanix.dev/reference/prism_central/v3/api/images/postimageslist
HTH. :)

Related

Body of a request is empty [duplicate]

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

Basic Auth is not working with Axios post Nodejs

I am trying to send a request using axios post with basic authorization. It is working fine with postman but not working when I try to send via code.
axios.post(`my-url`, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic **KEY_HERE**',
},
data: {
'id': 'event_order',
'date': '2021-09-09'
}
}).then(async (response) => {
console.log(response.data)
})
It is returning 401 Unauthorized. But, it works as excepted when I call it via Postman:
Postman Setup Image
Did you add your domain to whitelist in your cors module? If not:
app.use(cors({ origin: "PROTOCOL://DOMAIN:PORT", credentials: true }));
edit: Ok, sorry, I was confused and thought you were sending a frontend axios post request to your own NodeJS server. If possible, could you be more precise. But try passing in your headers/auth as the third argument-- since you're passing in everything in the second argument, the API is not parsing out your headers since its part of the data parameter.
const data = {
'id': 'event_order',
'date': '2021-09-09'
}
axios.post(`my-url`, data, {
headers: {'Content-Type': 'application/json'},
auth: {
username: "YOUR_USERNAME",
password: "YOUR_PASS"
}
})
.then(async (response) => {
console.log(response.data)
})
Also try and post the network errors, if you can.

Agora.io : Having issue with acquire POST call REST API in cloud recording

I am trying to set up cloud recording in Agora.io video call.According to agora docs first step is to call acquire API.
Initially I had issue with unescaped character is URL using axios NodeJS so I used encodeURI to bypass that error.My requests config is as follows
{
"url":"https://api.agora.io%E2%80%8B/v1%E2%80%8B/apps%E2%80%8B/xxxxxxx_APPID_xxxx%E2%80%8B/cloud_recording%E2%80%8B/acquire",
"method":"post",
"data":"{\"cname\":\"5f30xxxx-xx33-xxa9-adxx-xxxxxxxx\",\"uid\":\"75\",\"clientRequest\":{\"resourceExpiredHour\":24}}",
"headers":{
"Accept":"application/json, text/plain, */*",
"Content-Type":"application/json;charset=utf-8",
"Authorization":"Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"User-Agent":"axios/0.19.2",
"Content-Length":102
},
"transformRequest":[
null
],
"transformResponse":[
null
],
"timeout":0,
"xsrfCookieName":"XSRF-TOKEN",
"xsrfHeaderName":"X-XSRF-TOKEN",
"maxContentLength":-1
}
I get this response
Error: Request failed with status code 400
I have enabled cloud recording in agora console still the same error.
I would recommend taking a look at the Agora Postman Collection, which helps provide properly formatted requests.
In your request you are missing the
For example your request should look like this:
var axios = require('axios');
var data = JSON.stringify({"cname":"demo","uid":"527841","clientRequest":{ "resourceExpiredHour": 24}});
var config = {
method: 'post',
url: 'https://api.agora.io/v1/apps/<xxxx_APPID_xxxx>/cloud_recording/acquire',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Here is a guide I've written for getting started with the Postman Collection for Agora's Cloud Recording.

Unexpected token N in JSON at position 0

guys. I have a than error in my NodeJS rest API, and can't resolve this.
My idea is make a github login, this app working like this.
Href to github url returning a temporal code in callback.
Latter, send this temporal code to my REST API and with rest api make a fetch request to other endpoint of the github api, and this endpoint should return access_token=12345 (this access token is a example), for latter send this token to frontend, and convert the token in a JWT token and also send to frontend for latter storage in a localStorage to use it.
My code in NodeJS
router.post("/users/github/:code",function(req,res){
fetch('https://github.com/login/oauth/access_token/', {
method: 'GET',
client_id: 'xxxx',
client_secret: 'xxxx',
code: req.params.code,
accept: 'json',
})
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});
});
PD: I use node-fetch module for this. https://www.npmjs.com/package/node-fetch
The solution
router.post("/users/github/:code",function(req,res){
fetch('https://github.com/login/oauth/access_token/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: 'xxxx',
client_secret: 'xxxx',
code: req.params.code
})
}).then(function(res) {
return res.json();
}).then(function(body) {
res.json(body);
});
});

How to pass JSON object from API to server

I am using React and node.js, and I've used react's fetch to POST some Login credentials to my restAPI in order to receive a webtoken...
fetch('http://localhost:8080/api/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.username_login,
password: this.state.password_login
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson); //this is the object containing the token
})
.catch(function(error) {
console.log("request failed");
})
}
so responseJson is the the object containing my web token. The request was successful and now I've passed it to the client. Now, I am thinking of saving it to a cookie.
How can I send this to the server? Should I make a POST request? If so how do I do that once the JSON object is received? If there is a better way, I would like to know.
Cookies are automatically passed along any HTTP request made with fetch

Resources