Azure Function axios POST empty Response - javascript

I am trying to make an axios call in my React frontend to get some information from the backend to access some information. When I log the response on the server, I see the required information, but in the axios call, I get data = "" for some reason.
ReactJS Axios call
await axios
.post(url, {
token: this.props.authUser.idToken.rawIdToken,
blob_path: blobPath,
container: container
},
config
)
.then((response) => {
if(response.data == ""){
console.log("nada");
debugger;
}
callback(response);
})
.catch((error) => {
debugger;
callback(error);
});
Azure Server Response Code
exit = (result) => {
console.log("---------- RESULT ------------");
console.log(result);
console.log("------ END RESULT ------------");
context.res = {
status: 200 /* Defaults to 200 */,
body: result,
headers: { 'Content-Type': 'application/json' },
};
context.done();
};
The response on the backend
The response on the frontend
EDIT: Axios is sending double requests and the old request's response gets ignored.

Related

How do I acquire the data in a json response from a POST request in Next/React?

I am using Next.js api route to handle a POST request then send a response back to the frontend. I have used Rapid API client extension to confirm there is a response being sent to the frontend. I just dont know how to handle it in the frontend.
Here is the code on the api route:
import clientPromise from "../../../config/mongodb";
export default async function userDetailsHandler(req, res) {
const body = req.body;
if (req.method == "POST") {
const client = await clientPromise;
const db = client.db("mood-board");
let emailQuery = await db
.collection("users")
.find({ email: body.email })
.limit(1)
.toArray();
let parsedData = JSON.parse(JSON.stringify(emailQuery));
res.status(200).json(parsedData)
console.log(parsedData)
} else if(req.method = "GET") {
}
}
In the following example, you use the fetch api to post the data which returns a promise. You can use then() which takes a callback function that you can use to operate on the data once that promise is returned.
Example:
useEffect(() => {
// POST request using fetch inside useEffect React hook
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React Hooks POST Request Example' })
};
fetch('https://reqres.in/api/posts', requestOptions)
.then(response => response.json())
.then(data => setPostId(data.id));
// empty dependency array means this effect will only run once (like componentDidMount in classes)
}, []);

axios GET request with form data in React JS

I want to implement the following cURL request (which is working) in react js using axios:
curl -k --request GET "BASE_URL_SERVER/sendText" --form "user_id="uidxxxx"" --form "sign_id="
I always get the same error: field sign_id not found, but technically I'm sending it, so I'm kind of desesperate.
var data = new FormData();
data.append('user_id', 'uidxxxx');
data.append('sign_id', '9');
const api = axios.create({
baseURL: BASE_URL_SERVER,
data: data,
headers: {
'Content-Type': `multipart/form-data; boundary=${data._boundary}`
},
timeout: 10000,
})
api.get('/sendText')
.then(response => console.log(JSON.stringify(response.data)))
.catch(error => { console.log(error) })
I've also tried adding '...getHeaders()' to the headers section but React says it is not a function; I've read in other posts that it has something to do with the browser
thanks in advance
ps: it is a pretty similar problem to this one, but none of the solutions worked for me
[UPDATE]
I ended up implementing it with POST, which is better for posting Form Data; no headers are needed, the browser automatically adds them:
var data = new FormData();
data.append('user_id', user_id);
data.append('sign_id', sign_id);
const api = axios.create({
baseURL: BASE_URL_SERVER,
timeout: TIMEOUT_SERVER,
})
api.post('/sendText', data)
.then(response => console.log(JSON.stringify(response.data)))
.catch(error => { console.log(error) })
You have a mistake, you try to send data via axios for POST and method is GET...
So that, You need to Change Method to be POST to can Post form data or you need to change it to url param or url path base on your api to be WORK as a GET...
Base on your curl, your case is you need a GET:
// Make a request for a user with a given ID
axios.get('/sendText?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
sendText: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
Also, you can save all config in instance and share it for all nested of write it again and again..
for example:
// Common Axios Instance Config
const axiosConfig = {
baseURL: process.env.REACT_APP_API_ENDPOINT,
};
// Create Default Axios Instace
const instance = axios.create(axiosConfig);
I think base on your example this will work, but not sure sine I'm not test it..:
var data = new FormData();
data.append('user_id', 'uidxxxx');
data.append('sign_id', '9');
const api = axios.create({
baseURL: 'https://193.146.38.4:56076',
headers: {
'Content-Type': `multipart/form-data; boundary=${data._boundary}`
},
timeout: 10000,
})
api.get('/sendText', {
user_id: 111,
sign_id: 2222
)
.then(response => console.log(JSON.stringify(response.data)))
.catch(error => { console.log(error) })
For more details view this url

Response Header not accessible in JS

I am using React + Redux on the front end and Spring for the backend. The reponse header contains Authorization header when viewed on browser and in postman but not when trying to access in javascript. I have added the photos showing response headers in network tab and on console tab. And also i am using axios for the request.
auth.js
...
export const authInit = (data) => {
return dispatch => {
dispatch(authInitStart());
axios.post('/login', data)
.then(response => {
if(response.status === 200){
const param = {
'Authorization': response.headers.Authorization
};
console.log("Authorization----" + JSON.stringify(response));
console.log("Param----" + JSON.stringify(param));
localStorage.setItem('Authorization', param['Authorization']);
dispatch(authInitSuccess(param['Authorization']));
}else{
dispatch(authInitFail('Request failed'));
}
}).catch(err => {
dispatch(authInitFail('Network error'));
});
};
};
...
param object is empty here
What can be the issue?
Access-Control-Expose-Headers: Authorization
response.headers.get('Authorization')
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

Receving "500 Internal Server Error" on Post Request to Firebase-Cloud-Function Endpoint

I'm trying to make a POST request using axios to my firebase cloud-function on form submit in react app. But I get '500' error everytime I make a request with an html-page response This app works best with javascriot enabled.
Latest Update:
It looks like there is no issue with cloud function
code. Rather more of a react-component issue. I used Postman to send
the POST request with header prop Content-Type set to application/json
and sending body in raw format {"email": "example_email"} and got
expected response from the cloud function. But when sent the request from
react component above, I get an html file response saying the app
works best with javascript enabled
I've tried setting Content-Type to both Application/json and multipart/form-data as I suspected it to be an issue but still got no luck.
Following is my code for cloud function and react submit form:
Cloud Function
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true })
const runThisFunc1 = require(./libs/runThisFunc1);
const runThisFunc2 = require(./libs/runThisFunc2);
exports.wizardFunc = functions.https.onRequest((request, response) => {
cors(request, response, () => {
let email = request.body.email;
try {
return runThisFunc1(email)
.then(data => {
console.log("Word Done by 1!");
return runThisFunc2(data);
})
.then(res => {
console.log("Word Done by 2!");
return response.status(200).send("Success");
})
.catch(err => {
console.error("Error: ", err.code);
return response.status(500).end();
});
}catch(err) {
return response.status(400).end();
}
});
});
React-Form-Component Snippet
import axios from 'axios'
...
handleSubmit = e => {
e.preventDefault()
const { email } = this.state
axios({
method: 'post',
url: `${process.env.REACT_APP_CLOUD_FUNCTION_ENDPOINT}`,
data: { email: email },
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
})
.then(res => {
//do something with reponse here
})
.catch(error => {
console.error(error)
})
}
...
Is there something wrong I am doing in the code or the request config is wrong?

Unable to send get request with headers using axios

Able to get the response in postman. But unable to get in axios. Getting html as response. What would be the problem?
import axios from 'react-native-axios';
var config = {
headers: {
'Content-Type': 'Application/Json',
'JsonStub-User-Key': '__USER__KEY',
'JsonStub-Project-Key': '__PROJECT__KEY'
}
};
export async function menuListByCategories() {
// simulate an asynchronous operation
const url = "http://jsonstub.com/burgers";
axios.get(url, {config})
.then((response) = > {
console.log(response.data);
})
.
catch ((error) = > {
console.log("axios error:", error);
});
}
Update: check the response of this code
You can add data: {} in config in order not to have Content-Type removed by axios. Check the answer of the question below.
Jsonstub response not showing

Categories

Resources