ClientFunction: _axios2 is not defined - automated-tests

I'm running TestCafe for UI automation, using ClientFunctions to trigger API requests (so that I can pass along session cookies).
Currently I have a ClientFunction with fetch which works fine... except we're now testing IE 11 and Fetch is unsupported.
Fetch code:
const fetchRequestClientFunction = ClientFunction((details, endpoint, auth, method) => {
return window
.fetch(endpoint, {
method,
credentials: 'include',
headers: new Headers({
accept: 'application/json',
'Content-Type': 'application/json',
}),
body: JSON.stringify(details),
})
.then(httpResponse => {
if (httpResponse.ok) {
return httpResponse.json();
}
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
However when I try to switch it to axios... not so much:
import axios from 'axios';
const axiosRequest = ClientFunction((details, endpoint, auth, method) => {
return axios({
method,
auth,
url: endpoint,
data: details,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
timeout: 3000,
})
.then(httpResponse => {
if (httpResponse.status < 300) return httpResponse;
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
Tried using window.axios, and also passing axios as a dependency. I've also tried making the axios request without the ClientFunction... and despite getting response of 200, the website wasn't updated as expected.
Each time I either get _axios2 is not defined or window.axios is not a function. I would greatly appreciate some guidance here.

TestCafe ClientFunctions allow only serializable objects as dependencies. You need to have axios on the client side to send such a request.

Related

Post multiple logs to DataDog with 1 HTTP request

I want to post multiple logs to DataDog from a JS function, using a single HTTP request. Looking at the v2 docs for DataDog's 'send logs' POST endpoint, it sounds like this is possible:
For a single log request, the API ... For a multi-logs request, the API ...
But it's not clear to me from the docs how to actually send a 'multi-logs' request. I've tried the following:
const dataDogEndpoint = 'https://http-intake.logs.datadoghq.com/api/v2/logs';
const body = {
ddtags: 'env:production,status:info',
hostname: 'my-host',
message: ['My first production log.', 'My second production log.'],
service: 'my-service'
};
const response = await fetch(dataDogEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'DD-API-KEY': apiKey
},
body: JSON.stringify(body)
});
Perhaps unsurprisingly, this appears in DataDog as a single log with the following content:
[My first production log., My second production log.]
How can I achieve this?
Got it - this can be achieved by adding multiple log objects to the body like so:
const dataDogEndpoint = 'https://http-intake.logs.datadoghq.com/api/v2/logs';
const body = [{
ddtags: 'env:production,status:info',
hostname: 'my-host',
message: 'My first production log.',
service: 'my-service'
},{
ddtags: 'env:production,status:info',
hostname: 'my-host',
message: 'My second production log.',
service: 'my-service'
}];
const response = await fetch(dataDogEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'DD-API-KEY': apiKey
},
body: JSON.stringify(body)
});
(You'll probably want a loop instead of instantiating each log object separately.)

Pass variable from client to server-side in NEXTJS

I have already done this but Idk why when I try to apply it again in another code it does not work. So I have this code "Client side"
const response = await fetch("/api/ipfs", {method: "POST", DATA: "holaaaa"});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const result = await response.json()
console.log(result.result)
And this one that is the "Server side"
function uploadIPFS(req, res) {
axios.get(req.body).then(r => {
let metadata = r.data
res.status(200).json({ metadata: metadata });
}).catch(err => console.error(err))
}
export default function handler(req, res) {
if (req.method==='POST') {
uploadIPFS(req, res);
}
}
This is working with another api file I have, so I implement another file that is this one and in another function of the client side make a call to the new api file, the problem is that the variable I want to pass from client to server is the body one, the one that says "holaaaa", is it not working and it throws this error.
API resolved without sending a response for /api/ipfs, this may result in stalled requests.
Error: Cannot read properties of null (reading 'replace')
at dispatchHttpRequest (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\adapters\http.js:161:23)
at new Promise (<anonymous>)
at httpAdapter (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\adapters\http.js:49:10)
at dispatchRequest (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\dispatchRequest.js:58:10)
at Axios.request (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\Axios.js:109:15)
at Axios.<computed> [as get] (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\Axios.js:131:17)
at Function.wrap [as get] (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\helpers\bind.js:9:15)
at uploadIPFS (webpack-internal:///(api)/./pages/api/ipfs.js:17:11)
at handler (webpack-internal:///(api)/./pages/api/ipfs.js:37:9)
at Object.apiResolver (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\next\dist\server\api-utils\node.js:184:15) {
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.27.2'
},
method: 'get',
url: '',
data: undefined
},
url: '',
exists: true
}
any idea abt this?
The request to your API is made, but you are not adding anything to the request body. I think you need to change your DATA property in your fetch call to body:
const response = await fetch("/api/ipfs", { method: "POST", body: "holaaaa" });
Also, since you are passing that body parameter to the axios.get() method in your API handler, I assume it's supposed to be a URL?

Strava authorization working on local host but not when published to azure

The following code authorizes my strava account in my web app:
function Authorize() {
document.location.href = "https://www.strava.com/oauth/authorize?client_id=xxxxx&redirect_uri=https://localhost:44389/home/strava&response_type=code&scope=activity:read_all"
}
const codeExchangeLink = `https://www.strava.com/api/v3/oauth/token`
function codeExchange() {
fetch(codeExchangeLink, {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
client_id: '#ViewBag.cId',
client_secret: '#ViewBag.cSec',
code: '#ViewBag.code',
//need to do this to get a new refresh token that 'reads all' and issues a new Access Token - refer to comments below
grant_type: 'authorization_code'
})
})
.then(res => res.json())
.then(res => getActivities(res))
}
However, when I publish to azure and change the document.location.href code and redirect address (as below) to match my published app it fails with a 'bad request' error.
document.location.href = "https://www.strava.com/oauth/authorize?client_id=xxxxx&redirect_uri=https://xxxx.azurewebsites.net/home/strava&response_type=code&scope=activity:read_all"
Error is included below:
{"message":"Bad Request","errors":[{"resource":"Application","field":"redirect_uri","code":"invalid"}]}
Any help greatly appreciated
This was totally my error (embarrassingly). The issue was in my Strava Api App Settings, my call back uri was set to the default 'developers.strava.com'. All I had to do was change it to match my Published Web App uri 'xxxx.azurewebsites.net/home/strava' and it now works.

Axios post request to Firebase Auth REST API produces 400 error

I have an instance of Axios:
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://identitytoolkit.googleapis.com/v1'
});
export default instance;
Then I import it in my signup.vue file:
<script>
import axios from '../../axios-auth';
...
</script>
In that Vue file I have a signup form, which runs the following method once I hit the Submit button:
onSubmit() {
const formData = {
email: this.email,
age: this.age,
password: this.password,
confirmPassword: this.confirmPassword,
country: this.country,
hobbies: this.hobbyInputs.map(hobby => hobby.value),
terms: this.terms
};
console.log(formData);
axios.post('/accounts:signUp?key=my_key_goes_here', {
email: formData.email,
password: formData.password,
returnSecureToken: true
})
.then(res => {
console.info(res);
})
.catch(error => {
console.error(error);
});
}
I'm getting a 403 error - forbidden 400 error - bad request.
I tried to change headers:
instance.defaults.headers.post["Access-Control-Allow-Origin"] = "localhost";
instance.defaults.headers.common["Content-Type"] = "application/json";
But that didn't help.
I'm working from localhost and I saw that localhost is allowed by default. I tried also to add 127.0.0.1 to the list, but that also didn't help.
What am I missing? How can I make this request work?
If you get a 400 error it is maybe because you get an error from the API itself:
Common error codes
EMAIL_EXISTS: The email address is already in use by another account.
OPERATION_NOT_ALLOWED: Password sign-in is disabled for this project.
TOO_MANY_ATTEMPTS_TRY_LATER: We have blocked all requests from this device due to unusual activity. Try again later.
As a matter of fact, those errors return an HTTP Status Code of 400.
You can see the exact response message (e.g. EMAIL_EXISTS) by doing the following with axios:
axios.post('/accounts:signUp?key=my_key_goes_here', {
email: formData.email,
password: formData.password,
returnSecureToken: true
})
.then(res => {
console.info(res);
})
.catch(error => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
} else if (error.request) {
console.log(error.request);
} else {
console.log("Error", error.message);
}
});
See https://github.com/axios/axios#handling-errors
I agree with you as i have tried many approaches but was not getting the result. Hence i have tried to change the code.
You need to make two changes in your code.
1] You need to comment the instance.defaults.headers.post["Access-Control-Allow-Origin"] = "localhost"; because you are providing the authentication globally. As, firebase provides the feature of authentication and you are connecting the web app with REST API.
2] You need to add { headers: {'Content-Type': 'application/json' } in the axios.post() method to prevent it from CORS Error.
Following this approach i hope you can get the respective output.
Happy Coding!
Directly call
https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[yourkey]
No need to keep it in a separate file
Anyone who comes to the thread in future. I faced this issue and lost in debugging and worked with fetch. It was tiresome and took me a day but i made axios work. Here is the code.
const data = JSON.stringify({
idToken: authContext.token,
password: enteredNewPassword,
returnSecureToken: false,
});
// Send the valid password to the endpoint to change password
axios
.post(
"https://identitytoolkit.googleapis.com/v1/accounts:update?key=[Your Key]",
data,
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) => {
console.log(response.data);
})
.catch((err) => {
console.log(err.message);
});
Remember to Stringify the data you want to send. Stringify it outside of the http request and then pass that variable. Don't know why but this helps!
Lastly remember to add the header when sending the request to firebase. Make sure axios.post is on the same line. My formatter gave a line break which was also cause of error.
Hope it helps :)

Rails API not receiving fetch POST data from body

I have a route in Rails API '/api/pay'. My client side post request successfully hits the controller action, however nothing I send in the body: JSON.stringify('...') gets through to the back-end. Other post requests I have made work just fine with the same format.
export const payForItem = (payData) => {
return dispatch => {
dispatch(payForItemStart());
// ?userID=${data.userID}&adID=${data.adID}&price=${data.price}
const data = {userID: payData.userID, adID: payData.adID, price: payData.price}
fetch(`/api/pay`, {
method: 'POST',
header: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
})
Here is what payData looks like.
Rails Api back-end params
Probably you've got typo in headers section. Should be plural headerS with s:
headers: {
"Content-Type": "application/json"
}

Resources