Axios giving bad response with domain:port - node.js

In my node app, I'm trying to make a GET request to another server by Axios:
axios.get(`http://my-domain:2095/server/get-status`)
.then(result => { console.log(result.data) });
console.log shows me something like this (which is supposed to be JSON):
\x1F�\b\x00\x00\x00\x00\x00\x00\x03tα\x0E� \x14\x05�\x7F�3\x03/
��\f��8���\x12�\x04i\x17¿�j��g8\x15{Z%Ep�*��(9�\r<U�\x02\x06\r�x\x07���\��E0�^[OD�j��U�\x7F���r�)���mV�a�\x1D<�M�\x15R\x19���xc�\x04\x00\x00��\x03\x00\x02d&��\x00\x00\x00
The output is OK when I use ip:port in address. But not with domain:port.
Also The response of http://my-domain:2095/server/get-status is OK when I enter it in browser and Postman.
So what is the problem with Axios?

In axios v1.2.1, it fixed this error.
You need to add Accept-Encoding with application/json in axios.get header.
code in v 1.2.0
axios.get(`http://my-domain:2095/server/get-status`,
{
headers: {
'Accept-Encoding': 'application/json',
}
})
.then(result => { console.log(result.data) });
OR fixed in v1.2.1
axios.get(`http://my-domain:2095/server/get-status`)
.then(result => { console.log(result.data) })

Related

Unable to call Gitlab API with fetch in javascript

I have below API for fetching all jobs on a project in gitlab:
fetch("https://git.nmlv.nml.com/api/v4/projects/project_id_here/jobs", {
method: 'GET',
headers: {
'Authorization': 'Basic my-token-here'
},
'Accept': 'application/json',
'mode': "no-cors"
})
.then(response => {
console.log("hello")
return response.text();
})
.then(
text => {
var result= JSON.parse(text);
console.log(text)
}).catch(err=>{
console.log(err);
})
The above request works fine in Postman with the same token but here it is saying that the request is unauthorized. The problem is on the Gitlab API docs, they haven't specified how the request in javascript should look like. for your reference, here is the API that I want to call. I know something is incorrect in the way I have framed the API's header. Can anyone help me to find how to frame the request correctly.
Thanks
EDIT
The problem now is that when I run same request on browser inside an html page, response is coming fine. But it is not working inside a node script. The control is not going to then or catch block.

Basic Auth is not working with Axios post Nodejs

I am trying to send a request using axios post with basic authorization. It is working fine with postman but not working when I try to send via code.
axios.post(`my-url`, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic **KEY_HERE**',
},
data: {
'id': 'event_order',
'date': '2021-09-09'
}
}).then(async (response) => {
console.log(response.data)
})
It is returning 401 Unauthorized. But, it works as excepted when I call it via Postman:
Postman Setup Image
Did you add your domain to whitelist in your cors module? If not:
app.use(cors({ origin: "PROTOCOL://DOMAIN:PORT", credentials: true }));
edit: Ok, sorry, I was confused and thought you were sending a frontend axios post request to your own NodeJS server. If possible, could you be more precise. But try passing in your headers/auth as the third argument-- since you're passing in everything in the second argument, the API is not parsing out your headers since its part of the data parameter.
const data = {
'id': 'event_order',
'date': '2021-09-09'
}
axios.post(`my-url`, data, {
headers: {'Content-Type': 'application/json'},
auth: {
username: "YOUR_USERNAME",
password: "YOUR_PASS"
}
})
.then(async (response) => {
console.log(response.data)
})
Also try and post the network errors, if you can.

Why is the CORS error still appearing after enabling CORS in NodeJS app?

When I try to send some input from my form to my react backend, it prompts the CORS error even if I have CORS used in the server.js file. I have attached and image from the front-end and from the back-end
handleSubmit from my react app
handleSubmit = (event) => {
event.preventDefault();
console.log('Registration form was submitted');
console.log(this.state.fullname +' '+ this.state.age+' '+ this.state.adress)
fetch('https://localhost:4000/regUser', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.state.fullname,
age: this.state.age,
adress: this.state.adress
})
}).then( res => res.json())
.then(data => console.log(data))
}
This the CORS error is misleading in some cases.
And your case is one of those cases.
You are calling a post request on route /regUser but you are listening for get request on your server :
Change your server code to :
app.post("/regUser",(req,res)=>{
let data=req.body;
return res.send(data);
}
Note : As you are accessing req.body I have assumed that you want to use post in other cases just make sure you are sending and listening for same kind of request.
And as pointed in comments your server is not configured for https so use http instead.

Getting 400 Bad Request When POSTing to Get Transaction Token

I'm trying to integrate our website with Converge API with Hosted Payments Page. Here is the link to their documentation https://developer.elavon.com/#/api/eb6e9106-0172-4305-bc5a-b3ebe832f823.rcosoomi/versions/5180a9f2-741b-439c-bced-5c84a822f39b.rcosoomi/documents?converge-integration-guide/book/integration_methods/../../book/integration_methods/hosted_payments.html
I'm having troubles getting past the first step which is requesting a transaction token from their API endpoint. I'm sending a POST request from my server using axios with the correct parameters and URL, but when I try and POST i get 400 Bad Request. When I make the same request in POSTMAN I get a 200 response with the transaction token. I talked to their developers and they said that everything I was doing was correct and that nothing seemed odd within my code, so even they were stumped as to why I couldn't make a POST request to their endpoint. Obviously there is something within my code that their API is not liking, or else I wouldn't be here trying to find answers for this.
Here is how I'm making the POST request:
app.get('/converge_token_req', (request, response) => {
let params = {
ssl_merchant_id: '*****',
ssl_user_id: '*****',
ssl_pin: '*****',
ssl_transaction_type: 'ccsale',
ssl_amount: '1.00'
}
axios.post('https://api.demo.convergepay.com/hosted-payments/transaction_token', params, {
headers: { 'Content_Type' : 'application/x-www-form-urlencoded' }
}).then((res) => {
response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token')
response.send(error.message)
})
})
Here are the Request Headers:
I'm honestly out of ideas to try. The developers say that everything looks just fine yet I'm unable to make a successful request to their API. If anyone has any thoughts on this that would be great. Thanks!
This code below worked for me:
app.get('/converge_token_req', (request, response) => {
let params = {
ssl_merchant_id: '*****',
ssl_user_id: '*****',
ssl_pin: '*****',
ssl_transaction_type: 'ccsale',
ssl_amount: '1.00'
}
axios({
method: 'post',
url: 'https://api.demo.convergepay.com/hosted-payments/transaction_token',
params: params
}).then((res) => { response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token: ',
error)
})
})
I've since found out the solution to my problem. The issue here is that converge expects a x-www-form-urlencoded string that needs to be Stringified before submitting the request. I found a library that works well for this called qs and I used it like so:
let params = qs.stringify({ // need this if content_type is application/x-www-form-urlencoded
ssl_merchant_id: env.CONVERGE.MERCHANT_ID,
ssl_user_id: env.CONVERGE.USER_ID,
ssl_pin: env.CONVERGE.PIN,
ssl_transaction_type: request.query.type,
ssl_amount: request.query.amount,
ssl_email: request.query.email,
ssl_company: request.query.company,
ssl_avs_address: request.query.address,
ssl_avs_zip: request.query.zip,
ssl_description: request.query.desc,
})
axios.post('https://api.convergepay.com/hosted-payments/transaction_token', params, {
headers: {
'Content_Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then((res) => {
response.send(res.data)
}).catch((error) => {
console.log('there was an error getting transaction token')
response.send(error.message)
})
I think you could also get away with just using JSON.stringify() but this way worked for me.

Post request to graphql server not responding

I am trying to make a POST request to my graphql server that I have running on localhost:4000. To get my users I was using
getUsers(){
var query = `{users(id:""){username}}`
fetch('http://localhost:4000/graphql', {
method:'POST',
headers: {
'Content-Type' :'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
})
})
.then(res => res.json())
.then(res => console.log('data returned', res))
this wasn't working so I made a curl request to see what was wrong,
curl -X POST http://localhost:4000/graphql -H "Content-Type: application/json "-d "{"query": "{users(id:""){username}}"
After I ran this I kept getting,
Unexpected token q in JSON at position
After looking up this issue on google first I found a tutorial that I thought might be able to help. Following the tutorial I changed my code to
getUsers(){
var query = `{users(id:""){username}}`
fetch('http://localhost:4000/graphql', {
method:'POST',
headers: {
'Content-Type' :'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
})
})
//.then(r => r.json())
.then(res => res.text())
.then(text => console.log('data returned', text))
which still didn't log anything.
So i ran one last curl to attempt to solve this problem
curl -X POST http://localhost:4000/graph0ql -d "{"query": "{users(id:""){username}}"
which kept returning
{"errors":[{"message":"Must provide query string."}]}
Now I'm stuck and I don't know what to try next.
I checked the query string and it gives me the intended response in graphiql and the url is correct as well. My angular frontend server (from which I am making this request) is running on localhost:4200
Ok I feel pretty dumb. I didn’t call my function correctly. It works all that’s left is to actually use the data
The issue is how you're passing the query object. Try to update it into something like:
getUsers(){
var query = `query getUsers { users(id:"") { username } }`
fetch('http://localhost:4000/graphql', {
method:'POST',
headers: {
'Content-Type' :'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: query,
})
})
//.then(r => r.json())
.then(res => res.text())
.then(text => console.log('data returned', text))
}

Resources