How to convert a CURL request into an axios request? - javascript

I just successfully curled here:
curl -X POST https://jenkins-url/job/MyJob/job/some-job/job/master/build --user myemail:mypassword -H 'Jenkins-Crumb: mycrumb'
now I want to use axios inside my lambda
so I have this:
const axios = require('axios')
exports.handler = async (event) => {
const url = "my-url";
try {
const res = await axios.post(url, {}, {
auth: {
username: 'user',
password: 'passowrd'
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Jenkins-Crumb": "my-crumb"
},
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
console.log(res)
return {
statusCode: 200,
body: JSON.stringify(res)
}
} catch (e) {
console.log(e)
return {
statusCode: 400,
body: JSON.stringify(e)
}
}
};
but when I trigger the lambda it returns with: failed with the error "Request completed but is not OK"
not sure if I'm doing something wrong somewhere but seems to be everything is correctly mapped from CURL to axios

You have a few issues:
In your .then(...) handler, you are doing a console log, but you aren't returning anything from that function. Therefore, res is going to be undefined.
You're doing a JSON.stringify on res. res would be an axios response, not the response body. Stringifying the axios response is a bad idea, because it contains hefty object references and also circular references. You want res.data to give you the response data.
The error returned from Axios may also contain these heavy objects and circular references. In my experience, you can actually crash node when trying to serialize responses and errors from axios.
Here's how I'd modify your function:
const axios = require('axios')
exports.handler = async (event) => {
const url = "my-url";
try {
const res = await axios.post(url, {}, {
auth: {
username: 'user',
password: 'passowrd'
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Jenkins-Crumb": "my-crumb"
},
});
return {
statusCode: 200,
body: JSON.stringify(res.data)
}
} catch (e) {
console.log(e)
return {
statusCode: 400,
// Don't do JSON.stringify(e).
// e.response.data will be the axios response body,
// but e.response may be undefined if the error isn't an HTTP error
body: e.stack
}
}
};

Related

How can I resolve the error of 'serializing' from getServerSideProps in Next.js

I just changed the server from const server = "https://backend.yourguide.pk" to const server = "https://stage.yourguide.pk", and now this error is shown. How to resolve it?
getServerSideProps's code:
export async function getServerSideProps(context) {
let experience = [];
const server = 'stage.yourguide.pk';
try {
const data = await fetch(
`${server}/api/user/getallexperience?title=${context.params.experiencesTitle}`,
{
method: 'GET',
headers: { 'Content-Type': 'application/json' },
}
);
experience = await data.json();
} catch (error) {
console.log('error is ', error);
}
return {
props: {
title: context.params.experiencesTitle,
experience: experience.results,
},
};
}
error - SerializableError: Error serializing .experiences returned from getServerSideProps in "/".
Reason: undefined cannot be serialized as JSON. Please use null or omit this value.
For some reason, experience is being set to undefined, and undefined is not a valid JSON value. This can be addressed with the help of a check, like so:
export async function getServerSideProps(context) {
let experience;
const server = "stage.yourguide.pk";
try {
const data = await fetch(
`${server}/api/user/getallexperience?title=${context.params?.experiencesTitle}`,
{
method: "GET",
headers: { "Content-Type": "application/json" },
}
);
experience = await data.json();
} catch (error) {
console.log("error is ", error);
}
return {
props: {
title: context.params?.experiencesTitle || null,
experience: experience?.results || null,
},
};
}
Now, why you are getting undefined? Well, this can be because you are not using the correct endpoint, or path, or not giving the correct params, etc. Also, your error is saying .experiences while you have .experience.
Make sure you are not making any typos.

RTK query and response from server

updateTagCurrentValue: builder.mutation<any, {path: string, body: updateTagCurrentValueBody}>({
query: (args) => {
const {path, body} = args
return ({
url: `/v2/tags/${path}/values/current`,
method: 'PUT',
body: body,
})
},
transformResponse: (response) => {
return response
}
})
I am new in RTK, this mutation is working well, but I can not understand how to get a response from server? I see it in inspect network tab, I see my added data in the server, but the response comes null
const [updateTagCurrentValue, {error, isSuccess}] = useUpdateTagCurrentValueMutation()
const onSubmit: SubmitHandler = async (data) => {
let body: updateTagCurrentValueBody = {
value: {value: JSON.stringify(data)}
}
try {
let response = await updateTagCurrentValue({path: 'test', body}).unwrap();
console.log(response)
} catch (err) {
console.log(err)
}
}
I searched for solutions, and some people said add .unwrap() at the end of the call, but it didn't help. transformResponse also changes nothing, isSuccess changes from false to true after the second submission...

Nerlify: lambda response was undefined. check your function code again Response with status 500 in 583 ms

I'm trying to use netlify and its lambda function feature to run a node function. Based on https://css-tricks.com/using-netlify-forms-and-netlify-functions-to-build-an-email-sign-up-widget/.
Currently my netlify.toml has only the following:
[build]
functions = "./functions"
command = "npm run-script build"
mt submission.js:
// https://css-tricks.com/using-netlify-forms-and-netlify-functions-to-build-an-email-sign-up-widget/
require('dotenv').config();
const fetch = require('node-fetch');
console.log('to here');
const { LIST } = process.env;
const { B } = process.env;
exports.handler = async event => {
const email = JSON.parse(event.body).payload.data.EMAIL
console.log(email);
const asking = JSON.parse(event.body).payload.data.ASKING
console.log(asking);
var formData = {
'email': email,
'first_name': '',
'last_name': asking,
'lists[]': LIST
};
var encoded = Object.entries(formData).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
var endpoint = 'https://api.sendfox.com/contacts/?' + encoded;
const data = JSON.stringify(formData);
return fetch(endpoint, {
method: 'POST',
headers: {
Authorization: B,
'Content-Type': 'application/json',
},
body: JSON.stringify({ formData }),
})
.then(response => response.json())
.then(formData => {
console.log(`Submitted to Buttondown:\n ${formData}`)
})
.catch(error => ({ statusCode: 422, body: String(error) }))
// }
}
result:
Submitted to Buttondown:
[object Object]
◈ lambda response was undefined. check your function code again
Response with status 500 in 583 ms.
what am I doing wrong?
It's me, the author of the tutorial linked above!
Since I wrote the tutorial, node-fetch has updated with some breaking changes that make the code I wrote hard to debug.
A much more robust way to implement the same functionality in a netlify function would be to substitute the following:
const response = await fetch(
'https://api.buttondown.email/v1/subscribers',
{
method: 'POST',
headers: {
Authorization: `Token ${EMAIL_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ email }),
}
);
let responseText = await response.text();
console.log('response:', responseText);
return {
statusCode: response.status,
body: responseText,
};
This will return the proper status code, so you don't get the 'response was undefined' message. Plus, it'll properly log the response from buttondown, in case you need to do any further debugging.

React Native returns [Unhandled promise rejection: TypeError: Network request failed] when I'm making a Post Request

When I make a post request in React Native with Axios it returns a [Unhandled promise rejection: TypeError: Network request failed].
This is my json and my axios method
const credentials= {
NickName: "ricardo.luna",
Password: "123",
AccesoAplicacion: 1,
DerechosRangoInicial: 1000,
DerechosRangoFinal: 1012
}
const loginAxios = () => {
axios
.post('x.x.x.x/API/users', credentials)
.then(response => {
console.log(response.IdUser);
});
};
You need to pass your post params as FormData
let bodyFormData = new FormData();
bodyFormData.set('NickName', 'Fred');
bodyFormData.set('Password', '123');
bodyFormData.set('AccesoAplicacion', 1);
bodyFormData.set('DerechosRangoInicial', 1000);
bodyFormData.set('DerechosRangoFinal', 1012);
const loginAxios = () => {
axios({
method: 'post',
url: 'x.x.x.x/API/users',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
};
Or you can use querystring module to build your query string
const querystring = require('querystring');
const credentials= {
NickName: "ricardo.luna",
Password: "123",
AccesoAplicacion: 1,
DerechosRangoInicial: 1000,
DerechosRangoFinal: 1012
}
const loginAxios = () => {
axios
.post('x.x.x.x/API/users', querystring.stringify(credentials))
.then(response => {
console.log(response.IdUser);
});
};
just add after the .then() .catch(error=>{}) to handle the rejection and catch the error returned

fetch not executing with correct params - React Native

So I have a React Native app, making calls to my own external api via the fetch() native API. I am encountering a strange issue with my requests not being processed by fetch() correctly in only one context.
The calls are supposed to POST to /api/token_login.
Here is how I make my calls in the app:
#/src/services/post.js
import headers from './headers';
const APIURL = '******/api';
export default async (path, data, callback) => {
try {
const postData = {
method: 'POST',
credentials: 'include',
headers: new Headers(headers),
body: JSON.stringify(data)
};
const requestURL = `${APIURL}/${path}`;
const request = new Request(requestURL, postData);
const response = await fetch(request);
const res = await response.text();
if (response.ok) {
callback(null, res);
} else {
const error = res;
callback(error, null);
}
} catch (error) {
console.log('caught error: ', error);
}
};
#/src/services/auth.js
import post from './post';
export function TokenLogin(data, callback) {
post('token_login', data, callback);
}
...other functions
#/src/containers/Login.js
const data = {
user: {
auth_token: token,
},
};
return TokenLogin(data, (err, response) => {
const res = JSON.parse(response);
... do stuff
};
This function gets called on componentDidMount under certain conditions, which is the expected behavior. However, every day or so it suddenly stops sending the request to the passed in path, and sends a GET to /api/login instead. Changing the path passed into the function changes the behavior back to the expected one (i.e., passing in flurgl sends a POST request to .../api/flurgl with the body passed in correctly. Here is some debugging info:
// the logs:
=> Request method: POST url: https://*****/api/token_auth
=> Response object:
=> Response {type: "default", status: 404, ok: false, statusText: undefined, headers: Headers, …}
bodyUsed: true
headers: Headers {map: {…}}
ok: false
status: 404
statusText: undefined
type: "default"
url: "https://*******/api/login"

Categories

Resources