GetResponse 400 Bad Request - javascript

I'm trying to send a POST method to https://api.getresponse.com/v3/contacts from my Vue using axios. I'm unsure why I kept getting a 400 Bad Request. I've tried checking the Network tab on Mozilla dev tools but there doesn't seem to have any Response message it just returned me.
XHR OPTIONS https://api.getresponse.com/v3/contacts [HTTP/1.1 400 Bad Request 763ms]
I have double confirm from GetResponse documentation to add the Content-Type header to application/json and to set my API key as X-Auth-Token: api-key <API_KEY>.
NOTE: I am also getting CORS header ‘Access-Control-Allow-Origin’ missing but I believe it does not have anything to do with the Error 400.
Here are some code snippets from my Vue file.
axios-config.js
const instance = axios.create({
baseURL: process.env.VUE_APP_GET_RESPONSE_BASE_URL,
headers: {
'Content-Type': 'application/json',
'X-Auth-Token': `api-key ${process.env.VUE_APP_GET_RESPONSE_API_KEY}`,
}
});
Vue
import axios from "#/services/axios-config.js";
user: {
name: "",
campaign: {
campaignId: `${process.env.VUE_APP_GET_RESPONSE_CAMPAIGN_ID}`
},
email: "",
customFieldValue: {
customFieldId: "interest",
value: []
}
}
async callSubscribeAPI() {
try{
const response = await axios.post("/contacts",this.user);
console.log(response);
}catch(error){
console.log("error");
console.log(error);
}
}

This works for me:
(async() => {
const url = 'https://api.getresponse.com/v3/accounts';
const payload = await axios({
method: 'get',
url,
headers: {
"X-Auth-Token": "api-key 12345*****",
"content-type": "application/json"
}
});
console.log("payload", payload.data);
})()

Related

Is there a way to fix Recaptcha for ReactJS not working

Im trying to add captcha to my react app and the front end works just fine as expected. but when the backend calls the api to verify the captcha response (api) i get the following response { success: false, 'error-codes': [ 'missing-input-secret' ] }.
Now when i log the request to see what data is being sent. i get this image. as you can see the secret and response is being sent and my headers are correct but for some reason im getting an error.
heres my code:
const captchaRequest = await axios.post('https://www.google.com/recaptcha/api/siteverify', {
secret: config.captchaSecretKey,
response: captcha
}, {
headers: {
'Content-Type': 'application/json',
}
});
const captchaResponse = captchaRequest.data;
if (!captchaResponse.success) {
return res.status(401).json({
message: 'captcha failed',
success: false,
});
}
If someone could please let me know what im doing wrong let me know.
Had the same problem. you have to send the data as parameters and not in the body.
const captchaResponse = await axios({
method: 'post',
url: 'https://www.google.com/recaptcha/api/siteverify',
params: {
secret: SECRET,
response: CAPTCHA_RESPONSE
}
});

Trying to use fetch instead of axios to make a POST request, but the response from the fetch request returns an error, whereas axios doesn't

I have a function which uses Axios to send a POST request which goes through successfully and I get the right response. Now I want to try using fetch to do the exact same POST request. Unfortunately, the fetch request returns a 415 Unsupported Media Type response error and I have no idea why.
Currently:
onBeforeUnload = () => {
try {
const defaultPresence = {
presence: 'AVAILABLE',
message: '',
};
const url = getServerURL() + urls.PRESENCE;
axios.post(
url,
defaultPresence,
{
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
},
);
} catch (error) {
console.log(error);
}
}
The fetch code I've used to replace the Axios POST request.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
body: defaultPresence,
});
fetch does not recognise plain objects as the body.
If you want to send JSON then you need to encode the data and set the content-type header yourself.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(defaultPresence),
});

Error: Request failed with status code 422 in javaScript

I am using JS axios. I do not understand this error.
error:
Error: Request failed with status code 422
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)
This is my code:
const config = {
headers: { Authorization: `Bearer ${localStorage.getItem('id_token')}`,
headers: {
// Overwrite Axios's automatically set Content-Type
'Content-Type': 'application/json'
}
}
};
const bodyParameters = {
password:values.newPassword
};
setIsLoading(true)
//localhost:5000/api/v1/user/updatepassword
Axios.post('http://127.0.0.1:5000/api/v1/user/updatepassword',
bodyParameters,
config
)
And I am testing with fetch in chrome console. and got this error:
SyntaxError: Unexpected Identifier
I think your error is use 2 headers in config object. You can write it like this:
const config = {
headers: {
Authorization: `Bearer ${localStorage.getItem('id_token')}`,
'Content-Type': 'application/json'
}
}
422 status code means that your backend understands your request, but can't process the body (data) you sent.
You can try:
const config = {
method: 'post',
url: 'http://127.0.0.1:5000/api/v1/user/updatepassword',
headers: {
Authorization: `Bearer ${localStorage.getItem('id_token')}`,
'Content-Type': 'application/json'
},
body: {
password:values.newPassword
}
}
axios(config).then(response => console.log(response)).catch(err => console.error(err))
If you get the same error, check your backend gets all the fields it needs.
One more thing you can do: Try making the request on Postman and when it works you can get the axios code for it directly in the code section.

Localhost express mongodb server, fetch request to localhost returns 400 status

const data = {
email: "paul#Smith.com",
password: "PaulPass"
}
const body = JSON.stringify(data)
const paramsPost = {
method: "POST",
body: body
}
async function fetchContent() {
console.log(paramsPost)
let res = await fetch("http://localhost:3000/api/user/login", paramsPost);
console.log(res)
When I make run this function and fetch the response the console log prints out:
Response {type: "cors", url: "http://localhost:3000/api/user/login", redirected: false, status: 400, ok: false, …}
Could you tell me why it is doing this? What did I do wrong? When I make the request on postman the request gives me a status 200 and returns a JWT.
Thank you,
Snow
Changing the params to this:
const paramsPost = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: body
}
gives status 200!
I guess this is the answer but its very unsatisfying as what I wanted was the res.header
It's still undefined.

Axios Post Method to implement customized headers and with token value

I'm trying to write a Post method with Axios in NodeJS.
I have following things to pass as param in post method
url = http:/xyz/oauthToken
header 'authorization: Basic kdbvkjhdkhdskhjkjkv='\
header 'cache-control:no-cache'
header 'content-type: application/x-www-form-urlencoded'
data 'grant_type=password&username=user123&password=password123'
As I tried with following code but new to Axioz not sure how can exactly implement the header with grant type of body response.
var config = {
headers: {'Authorization': "bearer " + token}
};
var bodyParameters = {
data 'grant_type=password&username=user123&password=password123'
}
Axios.post(
'http:/xyz/oauthToken',
bodyParameters,
config
).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
Any help/suggestion would be appreciated :-)
Currently, axios does not make it convenient to use form-encoded data; it's mostly optimized toward JSON. It's possible, though, as documented here.
const querystring = require('querystring');
const body = querystring.stringify({
grant_type: 'password',
username: 'user123',
password: 'password123'
});
axios.post('http:/xyz/oauthToken', body, {
headers: {
authorization: `bearer ${token}`,
'content-type': 'application/x-www-form-urlencoded'
}
});

Categories

Resources