Axios response returning empty string - javascript

axios.post(
'http://localhost:3001/users',
{
username:user.username
}
).then((res)=> console.log(res.data))
Response From FrontEnd : data: ""
Response i get from postman :
[
{
"Username": "john4",
"Password": "",
"Email": "",
"ProfileImg": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAM1BMVEXk5ueutLeqsbTn6eqpr7PJzc/j5ebf4eLZ3N2wtrnBxsjN0NLGysy6v8HT1tissra8wMNxTKO9AAAFDklEQVR4nO2d3XqDIAxAlfivoO//tEOZWzvbVTEpic252W3PF0gAIcsyRVEURVEURVEURVEURVEURVEURVEURVEURVEURflgAFL/AirAqzXO9R7XNBVcy9TbuMHmxjN6lr92cNVVLKEurVfK/zCORVvW8iUBnC02dj+Wpu0z0Y6QlaN5phcwZqjkOkK5HZyPAjkIjSO4fIdfcOwFKkJlX4zPu7Ha1tIcwR3wWxyFhRG6g4Je0YpSPDJCV8a2Sv2zd1O1x/2WMDZCwljH+clRrHfWCLGK8REMiql//2si5+DKWKcWeAGcFMzzNrXC/0TUwQ2s6+LhlcwjTMlYsUIQzPOCb7YBiyHopyLXIEKPEkI/TgeuiidK/R9FniUDOjRDpvm0RhqjMyyXNjDhCfIMYl1gGjIMIuYsnGEYRMRZOMMunaLVwpWRW008v6fYKDIzxCwVAeNSO90BJW6emelYBRF/kHpYGVaoxTDAaxOFsfP9y8hpJ4xd7gOcij7JNGQ1EYFgkPJa1jQEiYZXRaRINKxSDUW9n+FT82lSKadkiru9/4XPqSLWOekGPoY05TAvLm9orm+YWuwHoBHkZKijNBJGmeb61eL6Ff/6q7bLr7yvv3vKGhpDRjvgjGaPz+gUg6YgcvpyAR2FIZ9U6nEEyZRTovmEU32KichpGn7C17XrfyH9gK/c0CMP05HZIM2uf9sEveizKveBy9/6Qt7o89ne33D525cfcIMW6ab+TMEukQbQbu+xu7X3A9bChmWaCeAkG17bpntwXgWxHaMzGPmUaR5dQZiKqRVeUZ3047fi3nAu28h4CHxCsZAgmEH8Y27jJAhm8c+5RQzRQNVGhVFSfxOYIjp/pP7RxzjevYXVGf4eLt+BJ1vCuLuLkrgABgCGXZ2wik5uty+oBvNirI6mkzhAf4Gsb58Hcm67Jzd+KwD10BYPLL3e0MjvKrgAULnOfveF/O4N2Xb9BZom3gJes3F9X5Zze8/6Yt09b4CrqsEjUv8oFBaR2rl+6CZr2xVrp24o/WitBKuGrrpl1+bFkmK2qXTON4VpbdfLa7o7y/WdLxG7lm2Lqh2clOwTegbvc/vj2U78CwhA87Bn8G5Nk3eOb0Nsr9flz3sG78UUtue4kpv1xvjg3TMay62BMlTlP+vrOMnJsRmt/ze0jsfkPPYdAH57hK+34PeOyc8XIXu5xT2HsUkdZz+adwg8HGFfQ3K5jtDvbUiO4Di9/ywHGrL88pDizZ++oTp+an+SMX/ndymUCwmHMdO7yuOx83pUx/eEMU0AvxWndwgidAqOZ8ypCwdEfvvEo6D9HwpA8wzvmOJEqAg9ySu8g4x0Hb9hSB/BANEKJ+LbPBU0lzbAJs4xt1AoshKkUGQmiH8/jJ0gdhTTLmSegHlPE0oOdXALnqDjKYh3px//fSgSWG8UqfrrIICzYYSJXRr9BSPbpNzw7gBjKjKOYI7ReIGqQRIap5+5MdjyvuDkExvGeXSlONWZAP3/AZBwJohU7QJRGU+cTVH18ELmRPNBmibW6MT/k1b0XhdkRBvyT6SB6EYv/GvhSmRNpGngRULsAlxMCGNXp7w3FfdEbTEEDdLI9TdIKRUzUesa3I461ER8cpNT7gMRhpKmYVS9ELOgCUQsa4SsulciKiLbY+AnHD8cpuhISsnxpamI84sbDq9qYJgf8wiiOBrC7Ml7M7ZECCqKoiiKoiiKoiiKoijv5AvJxlZRyNWWLwAAAABJRU5ErkJggg==",
"Followers": [],
"Following": [],
"__v": 0
}
]
im trying to post data and get a response from my server , the server is returning the right data when i use postman but when i use axios i get an empty string any help?
when i console.log(res)
{
"data": "",
"status": 205,
"statusText": "Reset Content",
"headers": {
"content-length": "2042",
"content-type": "application/json; charset=utf-8"
},
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"method": "post",
"url": "http://localhost:3001/users",
"data": "{\"username\":\"john4\"}"
},
"request": {}
}

You should handle your HTTP requests asynchronously with axios, utilizing async await. It just makes it so much cleaner.
Example:
const sendGetRequest = async () => {
try {
const response = await axios.post('http://localhost:3001/users', { username: user.username });
console.log(response.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
Calling the function sendGetRequest() in this case will send the post request, get the response and console log the response. And since it is utilizing try catch, if something goes wrong, it will console log the error.
Also make sure that your axios is properly setup. The correct headers etc. to match whatever you have with postman.

The issue was on my backend i sent res.status(205).json(user) instead of res.status(208).json(user) which somehow bugged it and caused it to send no data.

Related

my api is returning invalid JSON nodejs in post request while fectching

I am sending a post request in my next js app API (API is for updating address)
this is my fetching API code
async function handleSubmit() {
const data = { deliveryAddress, landmark, pincode, district, block, state }
const userID = localStorage.getItem("userID")
for (let item in data) {
let element = data[item];
if (element == "") {
toast.error(`${item} field must be filled`, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined
});
break;
}
}
console.log("above try");
console.log({ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify( userID)) });
try {
console.log("hello");
let res = await fetch(`${process.env.NEXT_PUBLIC_HOST}/api/updateaddress`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
})
let parsedResponse = await res.json()
console.log("response", parsedResponse);
}
catch (error) {
console.log(error)
}
}
and this code is returning an invalid Json error
this code line body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
this is what I got when I console.log my response body console.log({ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify( userID)) });
image of console error and the above-logged coder
Summary
I am getting a invalid JSON error but i think my JSON is correct and nothing wrong with api
I am getting a invalid JSON error
Well, your JSON is invalid…
body: [{ "address": JSON.parse(JSON.stringify(data)), "userid": JSON.parse(JSON.stringify(userID)) }]
That's an array, not JSON. You need to pass JSON to the body property.
Also JSON.parse(JSON.stringify(...)) does nothing useful in this context (since it is useful to deep clone simple objects and you don't mutate the value afterwards) so don't do that.
body: JSON.stringify([{ "address": data, "userid": userID }])
… but a 401 status means Unauthorized.

How to handle sign up a user error while using Firebase REST API

I've been trying to sign up a user using Firebase Rest API using Node & Axios HTTP library.
I'm able to create a new user with email and password.
But when email already exists in the database or password is less than 6 characters, it doesn't show the proper errors.
It just returns Request failed with status code 400
Here is my code.
const config =
{
headers:
{
'Content-Type': 'application/json',
},
};
data = {
'email': "test#test.com",
'password': "password123",
'returnSecureToken': true
}
try
{
let signup = await axios.post('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=API_KEY',data,config)
res.json(signup.data);
}
catch(err)
{
res.json(err);
}
Error I get.
{
"message": "Request failed with status code 400",
"name": "Error",
"stack": "Error: Request failed with status code 400\n at createError (/Users/user/NodeJS/FirebaseAuth/node_modules/axios/lib/core/createError.js:16:15)\n at settle (/Users/user/NodeJS/FirebaseAuth/node_modules/axios/lib/core/settle.js:17:12)\n at IncomingMessage.handleStreamEnd (/Users/user/NodeJS/FirebaseAuth/node_modules/axios/lib/adapters/http.js:244:11)\n at IncomingMessage.emit (events.js:327:22)\n at endReadableNT (_stream_readable.js:1224:12)\n at processTicksAndRejections (internal/process/task_queues.js:84:21)",
"config": {
"url": "https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=API_KEY",
"method": "post",
"data": "{\"email\":\"test#test.com\",\"password\":\"password123\",\"returnSecureToken\":true}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"User-Agent": "axios/0.21.0",
"Content-Length": 75
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
}
}
Expected error here is : Email already exists. But it doesn't return this error.
What could be the issue here ?
Thanks!
By default firebase doesn't return response in the error body but it can be extracted with.
console.log(err.response.data.error);
This is not mentioned in the official firebase docs.

Sending request to PayPal Payouts REST API returns HTTP code 204 and no content

I want to make a call to my server, which will then call the PayPal Payouts REST API to make a specific payment. I set up the necessary accounts and when I try it with Postman everything works great! I call the URL: https://api.sandbox.paypal.com/v1/payments/payouts with the token and Content-Type set to application/json and the body
{
"sender_batch_header": {
"sender_batch_id": "Payouts_2018_100013",
"email_subject": "You have a payout!",
"email_message": "You have received a payout from ****! Thanks for using our service!"
},
"items": [
{
"recipient_type": "EMAIL",
"amount": {
"value": "9.87",
"currency": "EUR"
},
"receiver": "****#*****.com"
}]
}
This will return something like
{
"batch_header": {
"payout_batch_id": "F5YLETFEWFLUS",
"batch_status": "PENDING",
"sender_batch_header": {
"sender_batch_id": "Payouts_2018_100012",
"email_subject": "You have a payout!",
"email_message": "You have received a payout from realnote! Thanks for using our service!"
}
},
"links": [
{
"href": "https://api.sandbox.paypal.com/v1/payments/payouts/F5YLETFEWFLUS",
"rel": "self",
"method": "GET",
"encType": "application/json"
}
]
}
with the HHTP Code 201 (Created). This is completely correct and I can see the status of my payment when calling the appropriate URL with the payout_batch_id from the answer.
However, if I try the same call from my NodeJS server there are problems. I get the token and everything works but then I create my request like this:
const options = {
url: "https://api.sandbox.paypal.com/v1/payments/payouts",
headers: {
'Content-Type': 'application/json'
},
auth: {
'bearer': token
},
form: {
"sender_batch_header": {
"sender_batch_id": "***_payment_***",
"email_subject": "You have a payout!",
"email_message": "You have received a payout from ****! Thanks for using our service!"
},
"items": [
{
"recipient_type": "EMAIL",
"amount": {
"value": "10.0",
"currency": "EUR"
},
"receiver": "*****#*****.com"
}]
}
};
I then send the request using the request module with this code:
request.post(options, function(err,httpResponse,body){
if (err) {
console.error('Sending money failed:', err);
} else {
console.log('Response from PayPal successful! Server responded with:', body);
//var payPalAnswer = JSON.parse(body);
}
})
But this will result in getting an answer with the status code 204 (No content) and it contains, no wonder, no content, so there is no possibility to get the status of my payment like with the server answer I got using Postman. Where is my error?
request.post(options, {data: "..."},function(err,httpResponse,body){
if (err) {
console.error('Sending money failed:', err);
} else {
console.log('Response from PayPal successful! Server responded with:', body);
//var payPalAnswer = JSON.parse(body);
}
})
You have to use your data as second parameter
The correct answer was to link the body in the request like this:
var dataObject = {"sender_batch_header": {
"sender_batch_id": "payment_",
"email_subject": "You have a payout!",
"email_message": "You have received a payout from *****! Thanks for using our service!"
},
"items": [
{
"recipient_type": "EMAIL",
"amount": {
"value": '10.0',
"currency": "EUR"
},
"receiver": "*******#personal.example.com"
}]
};
const options = {
url: "https://api.sandbox.paypal.com/v1/payments/payouts",
headers: {
'Content-Type': 'application/json',
'Content-Length': dataObject.length
},
auth: {
'bearer': token
},
body: dataObject,
json: true
};
Now PayPal returns the correct server answer 201.

Sendgrid integration with SAPUI5 app returns '400 Bad Request' on POST but works on Postman

I'm developing a cordova hybrid app that utilizes UI5 library. I need to be able to send as Email from the app so I decided to use Sendgrid API and, since I had issues with the NodeJS module, I'm creating an AJAX request. I've previously tested the request with Postman, being able to successfully send emails. But, as I tried to do the same request from the app, I've stumbled upon a status '400 Bad Request' without further information. Here goes the code snippet:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://api.sendgrid.com/v3/mail/send",
"method": "POST",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer [REDACTED]",
"cache-control": "no-cache"
},
"processData": false,
"data": {
"personalizations": [
{
"to": [
{
"email": "myemail#gmail.com"
}
],
"subject": "Contato do app"
}
],
"from": {
"email": "anotheremail#gmail.com"
},
"content": [
{
"type": "text/plain",
"value": formatEmail //variable with the email text
}
]
}
}
$.ajax(settings).then(
function success(response, status) {
dialog.close();
if (status == 202){
MessageBox.confirm('Mensagem enviada com sucesso', {
actions: [sap.m.MessageBox.Action.OK],
onClose: function(sAction){
that.onNavBack()
}
});
} else {
MessageBox.error('Erro!');
}
},
function fail(data, status){
dialog.close();
MessageBox.error('Request failed. Returned status of ' + status + ' DEBUGDATA: ' + JSON.stringify(data));
}
);
I really can't figure out the reason as to why this happens because the snippet generated by Postman is very similar to my code. Any help would be highly appreciated!
Thanks in advance
usually HTTP 400 means bad request and it means that you're passing the wrong parameters to the HTTP POST request.

Failed 401 Unauthorised error displayed in protractor

I am trying to automate the response which is getting generated in the postman tool but getting the error 401 unqutorized error. tried to resolve in many ways by giving the exact security token to the authorization-token but it didnt worked out.
//In this method the security token passed is newly generated and it works fine and produces response 200 in postman tool
async claimsetResponseOP(SecurityToken:string){
var options = {
method: 'POST',
url: 'http://nhsappchna8086/LMHIAService/api/v3/ValueSet/$expand',
//Giving header to the request
headers: {
'Authorization-Token': SecurityToken, // Here is the place where the security token is passed in the headers
'Accept': 'application/json+fhir',
'Content-Type' : 'application/json+fhir',
'Authorization-Type' : 'Native'
},
body: {
"resourceType ": "Parameters",
"parameter": [
{
"name": "ValueSet",
"resource": {
"resourceType": "ValueSet",
"status": "active",
"compose": {
"include": [{
"system": "http://snomed.info/sct",
"filter": [{
"property": "constraint",
"op": "=",
"value": "<<(*:R363698007=271629002)"
}
]
}
]
}
}
}
]
},
json:true,
resolveWithFullResponse: true
};
//Error gets displayed in below line as Failed 401 unautorized error
await requestp(options).then(async function(response){
await requestp(options).then(async function(Content){
if (await response.statusCode == 200){
var info = Content.body;
}
})
})
}
Below error gets displayed while executing: Can anyone please help in resolving
Failed: 401 - {"resourceType":"OperationOutcome","id":"AUTH-01","text":{"status":"additional","div":"Unauthorised"},"issue": [{"severity":"error","code":"security","details":{"text":"9254 - Unauthorised"}}]}
No. Manually when i run it is working fine.

Categories

Resources