Sending multiple cookies using Fetch in javascript - javascript

I am trying to send two cookies using Fetch in Javascript.
This is my function:
var cid_and_auth = process.argv[2];
const fetch = require("node-fetch");
function usePairService()
{
cid = cid_and_auth.split(" ")[1];
auth = cid_and_auth.split(" ")[0];
(async () => {
await fetch(AUTHENTICATIONURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': CONTENTTYPE,
'wpay-meta': userPairwpaymeta,
'cookie': 'cid'=cid,'auth'= auth,
},
body: JsonBody,
})
});;
}
I am trying to send cookies in the header, but it's giving an error, saying invalid left-hand die in expression. Any help will be appreciated.

'cid'=cid tries to assign the value of cid to the string value 'cid'. You cannot assign to a string, hence the error.
You have to build up a string of <key>=<value>; pairs. If you have each value in a variable you can either manually build the string, e.g. using template literals:
{
// ...
Cookie: `cid=${cid};auth=${auth}`,
}
or you could create an object from those variables and programmatically create the string (which makes it a bit easier to add more values later on):
const cookieData = {cid, auth};
// ...
{
// ...
Cookie: Object.entries(cookieData)
.map(([key, value]) => `${key}=${value}`)
.join(';'),
}

Related

Fetch API call not fetching cookies in expo react native?

I'm trying to send a post request to the server but the response does not contain 'set-cookie' header but the cookie is visible in postman.
This is the code:
axios.defaults.withCredentials = true;
let config = {
method: 'post',
url: 'https://app.bhive.fund/v1/api/account/signin',
headers: {
'Content-Type': 'application/json',
},
data: form
}
const res = await axios(config)
console.log(res.status)
console.log('set-cookie: ');
console.log(res.headers['set-cookie']);
console.log(res.headers);
return res;
This is the screenshot of the log
This is the screenshot of postman
That's because of the res.headers can't be accessed like an object.
You have to use the get()-method specified in order to get the cookie.
Try this instead of accessing the value right away by specifying the index with the brackets:
console.log(res.headers.get("Set-Cookie"));

MERN Stack, axios post current state to DB error 400 bad request [duplicate]

I am trying to create a postHTTP request with some form parameters that are to be set. I am using the axios with node server. I already have a java code implementation of constructing a url as given below:
JAVA CODE:
HttpPost post = new HttpPost(UriBuilder.fromUri (getProperty("authServerUrl"))
.path(TOKEN_ACCESS_PATH).build(getProperty("realm")));
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new NameValuePair("username",getProperty ("username")));
formParams.add(new NameValuePair("password",getProperty ("password")));
formParams.add(new NameValuePair("client_id, "user-client"));
I am trying to do the same thing in axios.
AXIOS IMPLEMENTATION:
axios.post(authServerUrl +token_access_path,
{
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}).then(function(response) {
console.log(response); //no output rendered
}
Is the approach to set these form params on the post request correct?
You have to do the following:
var querystring = require('querystring');
//...
axios.post(authServerUrl + token_access_path,
querystring.stringify({
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function(response) {
console.log(response);
});
If your target runtime supports it, Axios is able to accept a URLSearchParams instance which will also set the appropriate Content-type header to application/x-www-form-urlencoded
axios.post(authServerUrl + token_access_path, new URLSearchParams({
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}))
The same goes for the fetch API
fetch(url, {
method: "POST",
body: new URLSearchParams({
your: "object",
props: "go here"
})
})
Why pull in another library or module to do something so simple with pure vanilla JavaScript? It's really one line of JS to produce the desired data to submit in your POST request.
// es6 example
const params = {
format: 'json',
option: 'value'
};
const data = Object.keys(params)
.map((key) => `${key}=${encodeURIComponent(params[key])}`)
.join('&');
console.log(data);
// => format=json&option=value
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data,
url: 'https://whatever.com/api',
};
const response = await axios(options); // wrap in async function
console.log(response);
I agree with jhickok, no need to pull in an additional library however their code will not produce a correct result due to the usage of Object.entries, you would expect to see the following:
"format,json=0&option,value=1"
Instead Object.keys should be used.
const obj = {
format: 'json',
option: 'value'
};
const data = Object.keys(obj)
.map((key, index) => `${key}=${encodeURIComponent(obj[key])}`)
.join('&');
console.log(data); // format=json&option=value
Then of course...
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data,
url: 'https://whatever.com/api',
};
const response = await axios(options);
const body = new URLSearchParams();
body.append('param1', 'param1_value');
...
...
axios.post(url,body)

How to pass a query param in post call in Reactjs

I am new to reactjs.I am doing a post call but not sure, how to pass a boolean value in url as a query param in reactjs. For eg: http://www.abx.com?example=true. How do I pass this example in post api call.
Endpoint: API_SAMPLE: "/sample",
post call:
postCall() {
const config = {
headers: {
accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
product: {
body
},
};
return http
.post(this.API.API_SAMPLE, data, config)
.then((response) => {
return response.data;
})
.catch((error) => {
throw error;
});
}
i want to add a boolean value in my query param, how will i do that
You can use template literals to pass the variable to your URL.
const example = true;
const url = `http://abx.com/sample?example=${example}`
or use it this way:
return http.post(`${this.API.API_SAMPLE}?example=${example}`, data, config) {...}
wether you are using POST or GET you will have to modify the URL.
You can do this "dynamically" or you can use something like URLSearchParams:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
var URL = "http://example.com/search";
var searchParams = new URLSearchParams(URL);
searchParams.append("example", "true");
searchParams.toString() // "http://example.com/search?example=true";
Just make sure you support the correct browsers:
https://caniuse.com/#search=urlsearchparams

Error while sending a request to fluxpoint api

it's me again... Sorry for asking so many times a day, but I'm really an idiot.
So basically I'm trying to send a request to the fluxpoint api by using this code:
async welcome(username, avatarurl, background, membercount, icon, backgroundname, filename){
let req = {}
req.username = username;
req.avatar = avatarurl;
if (background == null) {req.background = "#aaaaaa"} else {req.background = background}
if (membercount) req.members = "Member #"+membercount
if (icon) req.icon = icon
if (backgroundname) req.banner = backgroundname
console.log(req)
let usedClient = axios.create({
baseURL: apiUrls[0],
timeout: 5000,
headers: {
'Authorization': this.token,
'Content-Length': 0,
'Content-Type': 'application/json'
},
data: JSON.parse(req),
responseType: 'arraybuffer'
})
console.log(usedClient)
console.log(apiUrls[0]+api1endpoints[1])
let res = await usedClient.get(api1endpoints[1])
return res
}
Here is the code I'm using for testing it:
const fluxpoint = require('./index')
const Client = new fluxpoint.Client("my fluxpoint token")
async function tt(){
let t = await Client.welcome("Koro~ (Baka)#7963", "https://cdn.discordapp.com/avatars/304541381798658048/36806f6ae648b9ebc8303443b0be101c.png", "#FFFFFF", 1, "neko", "space")
console.log(t)
}
tt()
And, here is the error the fluxpoint api sends me:
Failed to parse json, The input does not contain any JSON tokens. Excepted the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
I tried everything, but JSON.parse(my data) sends me Unexcepted token o in JSON at position 1
I'm being desesperate and I hope somebody can help me!
It seems you are parsing the raw json.It throws an error
JSON.parse takes string as parameter.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
And from official doc you cannot use data in get request.
https://github.com/axios/axios#request-config
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
}
So try passing the data
let res = await usedClient.get(api1endpoints[1],{
params: {
data: res
}
})
I've tested the endpoint it works only if responseType is 'text' or 'stream'

Zapier action to save file from API

I'm trying to create an action in zapier that will fetch raw bytes from my api and use it in zapier zaps after that.I actually stuck now, because none of what i've read in docs is working for me. Please any advice.
const options = {
url: `my test api call`,
method: 'GET',
raw: true,
headers: {
'Authorization': `Bearer ${bundle.authData.access_token}`
}
}
const stashPDFfunction = (z, bundle) => {
// use standard auth to request the file
const filePromise = z.request(bundle.inputData.options);
// and swap it for a stashed URL
return z.stashFile(filePromise);
};
var result = z.dehydrateFile(stashPDFfunction, {
options: options
});
return result;

Categories

Resources