Skip to content

Instantly share code, notes, and snippets.

@jplew
Created July 29, 2018 05:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jplew/f012347e060f291fbb7a7e0d4c0a4225 to your computer and use it in GitHub Desktop.
Save jplew/f012347e060f291fbb7a7e0d4c0a4225 to your computer and use it in GitHub Desktop.
Oxford API routes in NodeJS/Express
const axios = require('axios')
const oxfordDefine = 'https://od-api.oxforddictionaries.com/api/v1/entries/en'
const oxfordInflect =
'https://od-api.oxforddictionaries.com/api/v1/inflections/en'
const config = {
headers: {
Accept: 'application/json',
app_id: process.env.OXFORD_ID,
app_key: process.env.OXFORD_KEY,
},
}
module.exports = function(app) {
app.get('/api/oxford/define/:word', (req, res) => {
axios
.get(`${oxfordDefine}/${req.params.word}`, config)
.then(response => {
res.json(response.data)
})
.catch(err => {
handleError(err, res)
})
})
app.get('/api/oxford/define/:word/us', (req, res) => {
axios
.get(`${oxfordDefine}/${req.params.word}/regions=us`, config)
.then(response => {
res.json(response.data)
})
.catch(err => {
handleError(err, res)
})
})
app.get('/api/oxford/inflect/:word', (req, res) => {
axios
.get(`${oxfordInflect}/${req.params.word}`, config)
.then(response => {
res.json(response.data)
})
.catch(err => {
handleError(err, res)
})
})
}
// axios error handling reference
// https://github.com/axios/axios#handling-errors
function handleError(error, res) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error(
'RESPONSE ERROR STATUS: ',
error.response.status,
error.response.data
)
// res.sendStatus(error.response.status)
// next(error)
res.status(error.response.status).send(error.response.data)
// console.log(error.response.headers)
} else if (error.request) {
console.log('REQUEST')
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request)
res.send(error.request)
} else {
console.log('SOMETHING ELSE')
// Something happened in setting up the request that triggered an Error
console.error(error.message)
res.send(error.message)
}
// console.log(error.config)
}
@vivek1996
Copy link

Can I have the full setup or repo of your ful project ?

@jplew
Copy link
Author

jplew commented Jul 29, 2018

it's not public. You might want to check out these NPM packages: https://www.npmjs.com/package/oxford-dictionary-api
https://github.com/SleepyBandit/oxford-dictionary

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment