Created
July 29, 2018 05:28
-
-
Save jplew/f012347e060f291fbb7a7e0d4c0a4225 to your computer and use it in GitHub Desktop.
Oxford API routes in NodeJS/Express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
Can I have the full setup or repo of your ful project ?