I want to pass a .crt and .key files in order to authenticate and send Post Request using axios . I tired this :
const fs = require('fs')
axios({
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json'
},
method: 'post',
url: myURL,
cert: fs.readFileSync("../src/certif/mycrt.crt"),
key: fs.readFileSync("../src/certif/mykey.key"),
data: json_object
})
it failed to authenticate i get AuthenticationFailed error.
file are binary data and for that you have to use form data. You can not use json to send files
Related
Is there any way to send binary data of a file in body of a put request using nodejs and axios ?
you can use a FormData append your file to it , send it with axios then get it with multer in server side.
const data = new FormData()
data.append('multer_file_name', file, file.name)
axios.post("your_api", data, {
headers: {
accept: 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': undefined,
},
}).then((response) => {
})
you can get your file like this if you have an input :
const file = document.getElementById('your_input_id').files[0]
I wanted to know how to pass application credentials (or even user credentials through code) to apollo client like we do in axios.
In axios -
const data = await axios({
method: "POST",
url: `${SOME_URL}`,
auth: {
username: USER, //like this//
password: PASS,
},
data: req.body,
headers: { Accept: "application/json" },
});
For apollo client I have used apollo-link-http, my setup looks like this -
import fetch from "unfetch";
import { ApolloClient } from "apollo-client";
import { from } from "apollo-link";
import { onError } from "apollo-link-error";
import { createHttpLink } from "apollo-link-http";
const client = new ApolloClient({
link: from([errorLink, standardVariablesLink, typenameCleanerLink, createHttpLink({ uri: "https://graphql-backend/graphql", fetch })]),
cache,
});
I have tried adding credentials option in createHttpLink object as credentials: ${USER}:${PASS} OR as an object
credentials: {
user: USER,
password: PASS
}
but that didn't work.
Any help appreciated. Thanks!!
Question:
What is this auth in axios? ... a bit of searching: basic auth options! axios internally converts it to header.
Apollo client is not so nice ... you need to convert params into header itself and use this way:
const link = createHttpLink({
headers: {
authorization: "Basic btoa_converted_username_password";
},
The auth option in axios is just a shorthand way of constructing a Basic Authorization header. In order to construct the credentials value to include in the header, you do the following:
The username and the password are combined with a colon (aladdin:opensesame).
The resulting string is base64 encoded (YWxhZGRpbjpvcGVuc2VzYW1l).
So you can do something like:
createHttpLink({
uri: '...',
headers: {
Authorization: `Basic ${window.btoa(`${username}:${password}`)}`,
}
})
If you're running this code in Node.js, you would use the following instead of btoa:
Buffer.from(`${username}:${password}`).toString('base64')
Also note that if this code is running client-side, you probably want to inject the headers dynamically by using setContext instead.
I am using reactjs in my front end, so I am converting an image into base64 data and pass it to nodejs, In my backend I am trying send the base64 data to 3rd part API using fetch call, But it returns
401 unauthorization error
If I pass authorization in header nothing happens
const formData = new FormData();
formData.append('file', url);
const resp = await fetch(requestURL, {
method: 'POST',
headers: {
'Authorization': accessToken,
'Content-Type': 'multipart/form-data',
},
body: formData,
});
Can anyone help me with this?
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. :)
I am using a third party api which returns the image in Binary Media Data format. After getting this data, I want to upload this to Google Cloud Storage. To do this, I need to convert this data into Buffer. I've tried multiple times but failed.
I am using NodeJS, npm request module to call api to save image to google cloud storage.
Here is the code:
var binaryData = data;
var bufferData = new Buffer(data);
request({
method: "POST",
url: '/endpoint/upload',
headers: {
'cache-control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
},
formData: {
filename: {
value: fileBase64,
options: {
filename: 'test.jpg',
contentType: 'image/jpeg'
}
},
}
}, function(err, response, body){
console.log(body);
})
Your post request should follow the template described in the documentation. My post request looks like this:
req = https.request({
method: "POST",
protocol: 'https:',
hostname: 'www.googleapis.com',
path: '/upload/storage/v1/b/[bucket-name]/o?uploadType=media&name=[file-name]',
headers: {
'content-type': 'image/png',
'content-length': Buffer.byteLength(data),
'authorizatoin': Bearer [bearer-token]
}
}, (res) => {
console.log(res.statusCode);
console.log(res.statusMessage);
console.log(res.headers);
}
);
It also looks like you’re lacking authentication. You need to use OAuth 2.0 for Google Cloud Storage. Make sure the Cloud Storage JSON API is enabled too.
You need to obtain your file as a stream. Here's a useful post that specifies how to do that with axios. Once you download the file in the server, you can get it as a Buffer with fs.readFile.