What is the equivalent for this cURL request in axios - vue.js

What is the equivalent axios request for cURL request below?
curl -X POST \
http://159.89.90.5:5000/users/login \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"email": "pwerner#gmail.com",
"password": "password"
}'
I've tried using axios request as follow:
let axiosConfig = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
};
this.$http.post('http://159.89.90.5:5000/users/login', {"email": "pwerner#gmail.com", "password": "password"}, axiosConfig)
.then(response => {
console.log(response)
}).catch(function (error) {
console.log(error);
currentObj.output = error;
});
but I keep getting CORS error because the request doesn't fit with the request I made in cURL above. What am I missing here? if correct like curl request above I'll get email parameter with value pwerner#gmail.com
below is the error I've got when trying to make the request:
but if I use formData instead of using json for the same code, it works, and my server (flask framework) is already provided header: response.headers.add("Access-Control-Allow-Origin", "*") for solving CORS issue

Related

Issue sending in method to UrlFetchApp.fetch in GAS

Stupid question here, but I am pulling my hair out (i'm bald) as to what I could possibly be doing wrong. I am doing a UrlFetchApp.fetch in google app scripts:
var result = UrlFetchApp.fetch(url, { headers: headers });
When using this as my headers, it works:
var headers = {
Authorization: 'Bearer ' + getAccessToken()
}
Now I need to pass in 'method' as 'PUT' instead of the default of 'GET' (above), and and trying like this:
var headers = {
method : 'put',
headers : {
Authorization: 'Bearer ' + getAccessToken()
}
}
When I try sending this, it is not finding the token:
Exception: Request failed for https://api.spotify.com returned code 401. Truncated server response: {
"error": {
"status": 401,
"message": "No token provided"
}
How can I format the headers so that I can pass in the Authorization with token and also pass in 'method' as 'PUT'?
I see in the URLFetchApp.Fetch documentation for Google, that this is passed into options:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
headers Object a JavaScript key/value map of HTTP headers for the request
method String the HTTP method for the request: get, delete, patch, post, or put. The default is get.
Thank you so much for any help!
phi
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script. Ref And, from I know the call works with a simple GET method, your access token is valid.
curl --request PUT \
--url https://api.spotify.com/v1/me/player/play \
--header 'Authorization: ' \
--header 'Content-Type: application/json' \
--data '{
"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr",
"offset": {
"position": 5
},
"position_ms": 0
}'
In this case, how about the following sample script?
Sample script:
Please modify data for your actual situation.
var data = {
"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr",
"offset": {
"position": 5
},
"position_ms": 0
};
var options = {
method: 'put',
headers: { "Authorization": 'Bearer ' + getAccessToken() },
contentType: "application/json",
payload: JSON.stringify(data)
};
var url = "https://api.spotify.com/v1/me/player/play";
var res = UrlFetchApp.fetch(url, options);
console.log(res.getContentText());
Note:
I think that this request is the same as the curl command. But if an error occurs, please check the access token and the values in data, again.
References:
Start/Resume Playback
fetch(url, params)

Change curl statement to axios

I'm quite new to curl and I don't know how to convert this to axios statement
curl https://{subdomain}.zendesk.com/api/v2/users/{user_id}/password.json \
-X POST -d '{"password": "newpassword"}' -H "Content-Type: application/json" \
-v -u {email_address}:{password}
I can make this run in postman but I'm not sure to convert it to axios.
Below is my sample axios code but it I get a EOF error
const response = await axios.post(`https://${subdomain}.zendesk.com/api/v2/users/${userId}/password.json`,
{
"password": "12345678"
},
{
auth: {
username: `${email}/token`,
password: ZENDESK_API_KEY
}
})

Particle Photon API: Getting costumer token works on Postman but not with axios

I'm developing a react native application that combines a Photon Particle.
By following the documentation of a Two legged auth; before configure a device I need to get a claim code.
curl -X POST \
https://api.particle.io/oauth/token \
-H 'Accept: application/json' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=client_credentials&client_id=client_id&client_secret=clsecret&scope=customer%3Demail%40gmail.com'
When I do the request using CURL or even postman I got the desired results. But when I tried this using axios inside react native (iOS), I'm always getting the following error: Invalid or missing grant_type parameter.
The code below is my React Native code that is retrieving the data. And as you can see, I'm passing the grant_type.
costumerToken() {
const route = `${this.route}/oauth/token`;
const headers = {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
}
const body = {
"grant_type": "client_credentials",
"client_id": this.clientId,
"client_secret": this.clientSecret,
"scope": `customer=${this.costumerEmail}`
}
console.log(route, headers, body);
return axios.post(route, body, {headers: headers})
.then(res => {
return Promise.resolve(res);
})
.catch(err => {
return Promise.reject(err.response);
});
}
What is wrong?
When passing an Object as axios.post() body, it will send it as JSON but the Particle API expect it to be application/x-www-form-urlencoded. Axios docs go more deeply into this topic. To make it work you could change the code to:
customerToken() {
const route = `${this.route}/oauth/token`;
const headers = {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
}
const body = new URLSearchParams();
body.append("grant_type", "client_credentials");
body.append("client_id", this.clientId);
body.append("client_secret", this.clientSecret);
body.append("scope", `customer=${this.costumerEmail}`);
console.log(route, headers, body);
return axios.post(route, body, {headers: headers})
.then(res => {
return Promise.resolve(res);
})
.catch(err => {
return Promise.reject(err.response);
});
}

Authorization Header - Javascript Vuejs

I have a backend that performs BASIC authentication. I am passing the username/password encoded in curl as follows
curl -D- -X GET -H "Authorization: Basic cmFtcmFtOnBhc3N3b3Jk" -H "Content-Type: application/json" "http://localhost:9000/users/login"
and It works fine
Whereas in vue.js using vue-resource I am trying to do the same using
var options = {
url: 'http://localhost:9000/users/login',
method: 'GET',
headers:
{
'Authorization': 'Basic cmFtcmFtOnBhc3N3b3Jk'
}
}
context.$http(options).then(res => {
if (res.ok) {
cb({ authenticated: true })
} else {
cb({ authenticated: false })
}
})
But it is not getting authenticated. The request information i got from devtools is as follows
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-GB,en;q=0.8,fr;q=0.6,en-US;q=0.4
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
DNT:1
Host:localhost:9000
Origin:http://evil.com/
Referer:http://localhost:8080/Login
I do not see the authorization information being passed to the server. Am i doing something wrong ? Note : Both server and client are on localhost.
Thanks
vue-resource is retired so I don't think you should use it anymore. Instead, how about you use fetch instead as suggested and see if it works:
fetch('http://localhost:9000/users/login', {
method: 'POST',
headers: new Headers({
'Authorization: Basic cmFtcmFtOnBhc3N3b3Jk',
'Content-Type': 'application/json'
}),
body: JSON.stringify(req.body.payload)
})

Coinbase API revoke token

Is there any way to revoke coinbase oauth token? Coinbase documentation says that token is revoked after 2 hours, but I want my users to revoke access at any time they want.
I don't think there's a way to do this through the API, but you could link your users to https://coinbase.com/applications where they can revoke access themselves.
This is now allegedly supported (https://developers.coinbase.com/docs/wallet/coinbase-connect/access-and-refresh-tokens), but it does not work.
The access token can be revoked with the https://api.coinbase.com/oauth/revoke endpoint. Here is a curl request on how to use it:
curl --location --request POST 'https://api.coinbase.com/oauth/revoke' \
--header 'Authorization: Bearer ACCESS_TOKEN' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'token=ACCESS_TOKEN'
Or with Node.js (Source):
app.get('/refreshToken', async (req, res) => {
const data = qs.stringify({
'token': 'ACCESS_TOKEN'
});
const config = {
method: 'post',
url: 'https://api.coinbase.com/oauth/revoke',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ACCESS_TOKEN'
},
data
};
try {
const response = await axios(config);
res.send({ response: response?.data })
} catch (e) {
console.log("Could not refresh token", e.response.data)
}
})