Reputation: 409
I´m trying to make a post request to a third party API.
In this request I have to send my username and password on the header, and It will return a response header with the X-Auth_token. The problem is that I´m not getting the X-Auth-Token in the header if I make the posto from a client to my server and then to the API. If I make the request from Postman directly to the API url, it works fine.
This is the code:
SERVER
app.post("/signin", async (req, res) => {
console.log("BODY", await req.body);
try {
const xToken = await axios.post(loginUrl, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Username": req.body.username,
"X-Password": req.body.password,
},
});
console.log(xToken.headers);
//res.send(xToken);
} catch (error) {
console.log("SERVER Error: ", error.message);
}
});
CLIENT
const signin = async () => {
try {
const TOKEN = await axios.post("http://localhost:3000/signin", {
username: "AGU",
password: "MIOTTI",
});
console.log("TOKEN", TOKEN);
return TOKEN;
} catch (error) {
console.log("CLIENT Error: ", error.message);
}
};
signin();
What can be the problem?
some data of postman:
This is the response header when you try to make the post with postman directly to https://api.remarkets.primary.com.ar/auth/getToken:
and this is the response header when you make the reques to the serven on express:
Upvotes: 1
Views: 1212
Reputation: 9310
server.js
fileconst express = require("express")
const axios = require('axios')
const cors = require("cors")
const bodyParser = require('body-parser')
const corsOptions = {
exposedHeaders: 'Authorization',
};
const app = express()
app.use(cors(corsOptions))
app.use(bodyParser())
const loginUrl = 'https://api.remarkets.primary.com.ar/auth/getToken'
app.post("/signin", async (req, res) => {
console.log("BODY", await req.body);
const response = await axios.post(
url = loginUrl,
'',
config = {
headers: {
"X-Username": req.body.username,
"X-Password": req.body.password,
}
})
return res.send(response.headers["x-auth-token"])
});
app.listen(3000, () => { console.log("Listening on :3000") })
client.js
fileconst axios = require('axios')
const signin = async () => {
try {
const response = await axios.post("http://localhost:3000/signin", {
username: "<your id>",
password: "<your password>",
});
return Promise.resolve(response.data);
} catch (error) {
return Promise.reject(error);
}
};
signin()
.then(token => {
console.log('token is : ' + token);
})
.catch(error => {
console.log(error.message);
});
npm install express axios cors body-parser
Confirmed dependencies
$ npm ls --depth=0
@ D:\temp\working
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]
node server.js
node client.js
Axios get access to response header fields
Unable to access JSON property with "-" dash
Upvotes: 1