I am trying to get an acesss token from an api endpoint in postman using the
basic authentication
flow.
app.post('/epic', async (req:Request, res) => {
const code = req.query.code as string
const url = "https://api.epicgames.dev/epic/oauth/v1/token"
const values = new URLSearchParams({
code,
client_id,
client_secret,
scope: "basic_profile",
grant_type: "authorization_code",
})
console.log(code, values)
try {
const res = await axios.post(url, values, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
console.log(res.data)
return res.data
} catch (error: any) {
console.error(error.message)
throw new Error(error.message)
}
})
It keeps returning a 400 bad request. am i doing something wrong?
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
req.query
gives you the query parameters in the URL (e.g. https://www.somewebsite.com/api?code=supersecretcode
), whilst in postman you're providing it as the body of the request. You can go about this two ways:
Use query parameters in the URL instead of in the body in your postman request - this is as simple as moving everything that's in your request body to the URL (http://localhost:4000/epic?code=supersecretcode&grant_type=authorization_code&scope=basic_profile
)
Parse the request body in your server. I'm using the helpful body-parser
package in this example:
const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({ extended: false })
app.post('/epic', async (req: Request, res) => {
const { code } = req.body
const url = "https://api.epicgames.dev/epic/oauth/v1/token"
const values = new URLSearchParams({
code,
client_id,
client_secret,
scope: "basic_profile",
grant_type: "authorization_code",
})
// ...
})