Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Last active September 18, 2019 01:52
Show Gist options
  • Save joe-oli/0156a2a1157d67d52ed365b27cbffd4b to your computer and use it in GitHub Desktop.
Save joe-oli/0156a2a1157d67d52ed365b27cbffd4b to your computer and use it in GitHub Desktop.
http ajax library examples, e.g. fetch, axios, etc
//=== #1: axios and React.js =================================
import React, { Component } from "react"
import axios from "axios"
export default class extends Component {
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/users/1")
.then(response => {
console.log(response.data)
//typically this.setState({...}) here, so you can use whatever data.
})
.catch(err => {
console.error(err)
})
}
render() {
return (
<div>
<span>Page Content Goes Here</span>
</div>
)
}
}
//=== #2: Node.js, no extra libs required. =================================
// GET exmaple
const https = require("https")
https.get("https://jsonplaceholder.typicode.com/todos/1", function(res) {
res.setEncoding("utf8")
res.on("data", console.log)
res.on("error", console.error)
}).on("error", console.error)
// === #3: node-fetch =================================
//>npm install node-fetch --save
//similar to the built-in window.fetch of modern Browsers.
const fetch = require("node-fetch")
fetch("https://jsonplaceholder.typicode.com/todos/")
.then(function(response) {
return response.json()
}).then(function(data) {
console.log(data)
}).catch(function(error) {
console.log(error)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment