Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active December 19, 2018 22:27
Show Gist options
  • Save harrisonmalone/ea4b8f60c9690c27c2008f90c85672a2 to your computer and use it in GitHub Desktop.
Save harrisonmalone/ea4b8f60c9690c27c2008f90c85672a2 to your computer and use it in GitHub Desktop.
this was an example of sending up an axios post from react which we could then use on the express side to send back some kind of authenticated response
const express = require('express')
const cors = require('cors')
const app = new express()
const port = 5000
app.use(cors())
app.use(express.json())
app.get('/api', (req, res) => {
return res.send({message: 'this is the response'})
})
app.post('/api', (req, res) => {
const { username } = req.body
const { password } = req.body
return res.send({message: 'i got your post request'})
})
app.post('/api/auth', (req, res) => {
const { username } = req.body
const { password } = req.body
if (username === 'harrisonmalone' && password === 'password') {
return res.send('you are authed')
}
else {
return res.send('you are not authorized')
}
})
app.listen(port, () => {
console.log('listening to port 5000')
})
import React, { Component } from 'react';
import axios from 'axios';
import './App.css';
const authRequest = axios.create({
baseURL: 'http://localhost:5000/api',
headers: {
username: 'harrisonmalone',
password: '123456'
}
})
class App extends Component {
componentDidMount() {
// fetch('http://localhost:5000/api')
// .then((res) => {
// return res.json()
// })
// .then((json) => {
// console.log(json)
// })
// can now use authRequest.get()
axios.get('http://localhost:5000/api')
.then((res) => console.log(res))
}
handlePost() {
const user = {
username: 'harrisonmalone',
password: 'password'
}
console.log('clicked')
// can now use authRequest.post('', user)
axios.post('http://localhost:5000/api', user)
.then((res) => console.log(res.data))
}
handleAuth() {
const user = {
username: 'harrisonmalone',
password: 'password'
}
// can now use authRequest.post('/auth', user)
axios.post('http://localhost:5000/api/auth', user)
.then((res) => console.log(res.data))
}
render() {
return (
<div>
<button onClick={this.handlePost}>Make post request</button>
<button onClick={this.handleAuth}>Make auth post request</button>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment