'Connect Netlify React aplication with MongoDB Atlas using Axios
I'm build an simple website and i have a form that capture {name, email, phone and menssage}. I'm using Mongo Atlas to store my datas. I did deployed my React Frontend using Netlify and i need to GET and POST datas using Axios. The aplication works localy with baseURL='http://localhost:3333', but i need thats works with my deploy frontend. How i can change this URL to my Netlify deploy GET and POST on mongo atlas?
- BACKEND FILES
index.js
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const routes = require('./routes');
const cors = require('cors');
const app = express();
mongoose.connect(`mongodb+srv://MYUSER:[email protected]/myFirstDatabase?retryWrites=true&w=majority`, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.use(routes);
const PORT = process.env.PORT || 3333;
app.listen(PORT, () => {
console.log(`BACKEND EXECUTANDO NA PORTA: ${PORT}`)
});
LeadController.js
module.exports = {
//Listar Leads
async index(req, res) {
const leads = await Lead.find();
return res.json(leads);
},
//Cadastrar Lead
async store(req, res) {
const { name, email, phone, msg } = req.body;
let lead = await Lead.insertMany({
name: name,
email: email,
phone: phone,
msg: msg,
date: new Date(),
});
return res.json(lead);
},
};
routes.js
const LeadController = require('./controller/LeadController');
const routes = Router();
routes.get('/leads', LeadController.index);
routes.post('/insert', LeadController.store);
module.exports = routes;
- FRONTEND FILES
api.js
import axios from 'axios';
const api = axios.create({
baseURL:'https://localhost:3333'
});
export default api;
function request
async function handleNewLead(e) {
e.preventDefault();
await api.post('/insert', {
name: name,
email: email,
phone: phone,
msg: msg,
})
setName('');
setEmail('');
setPhone('');
setMsg('');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
