I'm using React for testing connection to the RDS database from my local client and local server. For first few tries, my demo application works perfectly but after few tries, it seems like my code fails to make connection to the database nor wants to make connection to each other. Can anybody tell me what I could've missed in my codes?
ps. I know my code isn't clean. There may exist some unnecessary codes but please ignore them.
I have been constantly testing and I figured out the not responding cycle is getting shorter which I think the problem is related to the cache data (if that makes sense - I'm completely new to react!).
Client
import React, {useState,useEffect} from 'react';
import './App.css';
import Axios from 'axios';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
function App() {
const [title, setTitle] = useState('');
const [sAuthor, setAuthor] = useState('');
const [dateTime, setDateTime] = useState('');
const [desc, setDesc] = useState([]);
const submitButton = () => {
console.log("submit")
Axios.post('http://localhost:3001/post', {
time: dateTime,
author: sAuthor,
})
.then((response)=>{
console.log("responsed");
});
Axios.get('http://localhost:3001/get').then((response)=>
{
console.log("got");
setDesc([]);
setDesc(response.data);
enlist();
});
}
const enlist = () => {
console.log("enlist");
console.log(desc)
desc.map((val)=>{
return <h2>"STOCK NAME:"</h2>
})
}
useEffect(()=>
{
Axios.get('http://localhost:3001/get').then((response)=>
{});
},[])
useEffect(()=>
{
console.log(desc);
})
return (
<div className="App">
<h1>CRUD APPLICATION</h1>
<div className="form">
<input type = "text" name = "AI_TITLE" onChange={(e)=>{
setTitle(e.target.value)}}/>
<h3>TITLE</h3>
<input type = "text" name = "AI_AUTHOR" onChange = {(e)=>{
setAuthor(e.target.value)}}/>
<h3>STOCK NAME</h3>
<DatePicker format={"yyyy-MM-DD"} selected={dateTime} onChange={(date) => setDateTime(date)} />
<button className = "button" onClick={submitButton} >submit</button>
{desc.map((val)=>{
return (
<h1>STOCK: {val.AI_STOCKCD}</h1>
)
})}
</div>
</div>
);
}
export default App;
Server
const express = require('express');//create express server
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');
const cors = require('cors');
app.use(cors());
const db = mysql.createPool({
host: 'somehost',
user: 'someuser',
password: 'somepassword',
port: 0000,
database: 'smms2'
})
app.use(express.json())
app.use(express.urlencoded({extended: true}));
var author = "";
var time = "";
// recieving request from client
app.post("/post",(req, res)=>{
author = req.body.author;
time = req.body.time;
console.log(1)
console.log(author)
console.log(time)
})
// sending request to db
app.get("/get",(req, rows, fields)=>{
const sqlSelect = "SELECT * FROM ai_board WHERE UPDATE_DT > '"+time+"' AND AI_AUTHOR = '" + author+ "';";
db.query(sqlSelect, (err, result) =>{
rows.send(result);
});
})
app.listen(3001, ()=>{
console.log("running on port 3001");
})
package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"devStart": "nodemon index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"mariadb": "^2.5.3",
"mysql": "^2.18.1",
"nodemon": "^2.0.7"
}
}
Related
I'm building a server-side rendered website with Node. I want to display a green alert box upon successfully updating data in updateSettings.js. Even though the user data (name and email) is updated on Compass correctly, I get a red alert box (error) with undefined as the message. In the browser console, I get a 'bad request' error from bundle.js.
Also, no code seems to run after the Axios PATCH request code
updateSettings.js
/* eslint-disable */
import axios from 'axios';
import { showAlert } from './alerts';
export const updateData = async (name, email) => {
try {
const res = await axios({
method: 'PATCH',
url: 'http://127.0.0.1:3000/api/v1/users/updateMe',
data: {
name,
email,
},
});
if (res.data.status === 'success') {
showAlert('success', 'Data updated successfully!');
}
} catch (err) {
showAlert('error', err.response.data.message);
}
};
Alerts.js
/* eslint-disable */
export const hideAlert = () => {
const el = document.querySelector('.alert');
if (el) el.parentElement.removeChild(el);
};
// type is 'success' or 'error'
export const showAlert = (type, msg) => {
hideAlert();
const markup = `<div class="alert alert--${type}">${msg}</div>`;
document.querySelector('body').insertAdjacentHTML('afterbegin', markup);
window.setTimeout(hideAlert, 5000);
};
Index.js
`
/* eslint-disable */
import '#babel/polyfill';
import { login, logout } from './login';
import { displayMap } from './leaflet';
import { updateData } from './updateSettings';
// DOM ELEMENTS
const leaflet = document.getElementById('map');
const loginForm = document.querySelector('.form--login');
const logOutBtn = document.querySelector('.nav__el--logout');
const updateDataForm = document.querySelector('.form-user-data');
// DELEGATION
if (leaflet) {
const locations = JSON.parse(leaflet.dataset.locations);
displayMap(locations);
}
if (loginForm)
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const password = document.getElementById('password').value;
const email = document.getElementById('email').value;
login(email, password);
});
if (logOutBtn) logOutBtn.addEventListener('click', logout);
if (updateDataForm)
updateDataForm.addEventListener('submit', (e) => {
e.preventDefault();
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
updateData(name, email);
});
`
Running the node debugger indicates that process.env.NODE_ENV is undefined but I'm using dotenv for this so it should be working just fine. In any case, the login functionality which is quite similar and uses axios runs just fine.
App.js
const path = require('path');
const express = require('express');
const morgan = require('morgan');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
const hpp = require('hpp');
const cookieParser = require('cookie-parser');
// eslint-disable-next-line node/no-deprecated-api
const exp = require('constants');
const AppError = require('./utilities/appError');
const globalErrorHandler = require('./controllers/errrorController');
const tourRouter = require('./routes/tourRoutes');
const userRouter = require('./routes/userRoutes');
const reviewRouter = require('./routes/reviewRoutes');
const viewRouter = require('./routes/viewRoutes');
const app = express(); //express is a function which upon calling will add a bunch of methods to the app variable
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
// 1.GLOBAL MIDDLEWARES
// Serving static files
// app.use(express.static(`${__dirname}/public`));
app.use(express.static(path.join(__dirname, 'public')));
// Set Security HTTP headers
app.use(helmet());
// Development logging
console.log(process.env.NODE_ENV);
if (process.env.NODE_ENV === 'development') {
// the readinng of the process only needs to happen once, and the process is the same no matter which file we're in
app.use(morgan('dev'));
}
// Limit requests from same API
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: 'Too many requests from this IP, please try again in an hour',
});
app.use('/api', limiter);
// Body parser: reading data from body into req.body
app.use(express.json({ limit: '10kb' })); //'express.json' here is middleware
app.use(express.urlencoded({ extended: true, limit: '10kb' }));
app.use(cookieParser());
// Data sanitization against NoSQL query injection
app.use(mongoSanitize());
// Data sanitization agains XSS
app.use(xss());
// Prevent parameter pollution
app.use(
hpp({
whitelist: [
'duration',
'ratingsAverage',
'ratingsQuantity',
'maxGroupSize',
'difficulty',
'price',
],
})
);
// Test middleware
app.use((req, res, next) => {
// we have access to the requestTime property; assuming we want to display the time of the request
req.requestTime = new Date().toISOString();
next();
console.log(req.cookies);
});
// 3. ROUTES: this is where we mount our routers
// these 3 routers are actually middlewares that we mount upon the paths
app.use('/', viewRouter); //mounted right on the root URL
app.use('/api/v1/tours', tourRouter); //we've created a sub-app with this
app.use('/api/v1/users', userRouter);
app.use('/api/v1/reviews', reviewRouter);
// this router is essentially a sub-app for each resource
// the request goes into middleware and when it hits the above line of code, it will match the url, and thus the tourRouter middleware function will run
app.all('*', (req, res, next) => {
next(new AppError(`Cant find ${req.originalUrl} on this server!`, 404));
});
app.use(globalErrorHandler);
module.exports = app;
/updateMe
exports.updateMe = catchAsync(async (req, res, next) => {
// 1) Create error if user POSTs password data
if (req.body.password || req.body.passwordConfirm) {
return next(
new AppError(
'This route is not for password updates. Please use /updateMyPassword',
400
)
);
}
// 2) Filter out unwanted field names that are not allowed to be updated
const filteredBody = filterObj(req.body, 'name', 'email');
// 3) Update user document
const updatedUser = await User.findByIdAndUpdate(req.user.id, filteredBody, {
new: true,
runValidators: true,
});
res.status(400).json({
status: 'success',
data: {
user: updatedUser,
},
});
});
package.json
"scripts": {
"start": "nodemon server.js",
"start:prod": "NODE_ENV=production nodemon server.js",
"debugger": "ndb server.js",
"watch:js": "parcel watch ./public/js/index.js --out-dir ./public/js --out-file bundle.js",
"build:js": "parcel watch ./public/js/index.js --out-dir ./public/js --out-file bundle.js"
},
"author": "Dave Odipo",
"license": "ISC",
"dependencies": {
"#babel/polyfill": "^7.12.1",
"axios": "^1.1.3",
"b": "^2.0.1",
"babel": "file:../../../../../../../../polyfill",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"dotenv": "^16.0.2",
"express": "^4.18.1",
"express-mongo-sanitize": "^2.2.0",
"express-rate-limit": "^6.6.0",
"helmet": "3.16",
"hpp": "^0.2.3",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.13.15",
"morgan": "^1.10.0",
"nodemailer": "^6.8.0",
"pug": "^3.0.2",
"slugify": "^1.6.5",
"validator": "^13.7.0",
"xss-clean": "^0.1.1"
},
"optionalDependencies": {
"win-node-env": "^0.6.1"
},
"devDependencies": {
"eslint": "^8.23.1",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsx-a11y": "^6.6.1",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react": "^7.31.8",
"parcel-bundler": "^1.12.3",
"prettier": "^2.7.1"
},
"engines": {
"node": ">=8.0.0"
}
}
Please help
Try changing res.status(400).json({ to res.status(200).json({
I am trying to use Request-Promise-Native or Axios but getting error during execution. I am sharing my code. I am using dialogflow inline editior. I also try with post api but not working. I guess somewhere i am doing minor mistake. Please explain also it will help me to learn.
'use strict';
const axios = require('axios');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
const request = require('request-promise-native');
// this is GET api using axios
function Login(agent) {
const email = agent.parameters.email;
const password = agent.parameters.password;
const baseurl = 'http://demoapi:3000/login/buyerlogin';
var data = {"email" : email,"password": password};
return axios.get(baseurl, { params:
data})
.then(result => {
console.log(result.data);
console.log(`statusCode: ${result.statusCode}`);
agent.add(result.data);
}) }
// This Get API using Request promise native
function Login(agent) {
const email = agent.parameters.email;
const password = agent.parameters.password;
const baseurl = 'http://demoapi:3000/login/buyerlogin';
var data = {"email" : email,"password": password};
var sdata = JSON.stringify(data);
const options = {
method: 'GET',
uri: baseurl,
body: JSON.parse(sdata),
json: true
};
return request(options)
.then(result => {
console.log(result.data);
console.log(`statusCode: ${result.statusCode}`);
agent.add(result.data);
});
}
Package.json file
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "10"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "^2.2.0",
"firebase-admin": "^5.13.1",
"firebase-functions": "^2.0.2",
"dialogflow": "^1.2.0",
"dialogflow-fulfillment": "^0.6.1",
"request": "^2.88.2",
"request-promise-native": "^1.0.9",
"axios": "^0.21.1"
}
}
Please help me out. Is anything required please let me.
Thank You
I want to save data using mongodb query using middleware in node.js. please provide some code with example?
Try this. It works both for insert and update (upsert).
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient;
const mongodb_url = process.env.MONGO_URL || "mongodb://localhost:27017";
const mongodb_dbname = 'test_db';
const port = process.env.PORT || 3006;
const app = express();
app.use(express.json())
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json({ extended: true}));
app.post('/api/post/:identifier', (req, res) => {
const identifier = req.params.identifier;
const content = req.body.payload;
MongoClient.connect(`${mongodb_url}`, { useNewUrlParser: true }, (err, client) => {
if (!err) {
let db = client.db(mongodb_dbname);
db.collection('posts')
.updateOne(
{ identifier: identifier },
{ $set: { content: content } },
{ upsert: true }
)
.then((output) => {
res.status(202).send({ message: "Sent"});
})
.catch((error) => {
res.status(500).send({
error_code: 500,
error_message: `Error while updating data - ${error}`
});
});
client.close();
} else {
res.status(500).send({
error_code: 500,
error_message: 'Error while connecting to database'
});
}
});
});
app.listen(port, () => {
console.log(`API bootstrapped on port ${port}...`);
});
Use the following package.json file:
{
"name": "mongo-upsert",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongodb": "^3.6.0"
}
}
When invoked as localhost:3006/api/post/my-post with a request body containing:
{
"payload": "Hello world"
}
This code is going to upsert a MongoDB document like:
{
"_id" : ObjectId("5f3d272cbd52c9c109ea9baa"),
"identifier" : "my-post",
"content" : "Hello world"
}
Prerequisites for the above code to work:
To have a working installation of mongodb
To have a database named test_db
To have a collection named posts
In this example, we are adding a post content, identified by an identifier, which for the sake of simplicity I have added as a path param in the POST definition.
Install dependencies using npm install.
Run the app using npm start.
Good luck.
Look into W3Schools NodeJS MongoDB.
I don't have enough rep to comment so here's an answer.
I am trying to fetch data from my local express server, and display it with react, but it seems that the index.html of the react app is being returned. If I check the network tab in the console and it shows that there is a fetch request with the name "projects/" and when I hover over it it shows "http://localhost:3000/api/projects". The console indicates that the problem is in line 13 of the react file which is "fetch('/api/projects/')". I've been trying for a while to fix this but can't seem to get it right. Code below
Express:
const express = require("express");
const app = express();
app.use(express.json());
let projects = [
{
id: 1,
title: "project1",
description: "One - description",
url: "www.One.com"
},
{
id: 2,
title: "project2",
description: "Two - description",
url: "www.Two.com"
},
{
id: 3,
title: "project3",
description: "Three - description",
url: "www.Three.com"
}
];
app.get("/api/projects", (req, res) => {
res.json(projects);
});
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
React:
import React from "react";
import "./App.css";
class App extends React.Component {
constructor() {
super();
this.state = {
projects: []
};
}
componentDidMount() {
fetch("/api/projects/")
.then(res => res.json())
.then(projects =>
this.setState({ projects }, () =>
console.log("Projects fetched...", projects)
)
);
}
render() {
return (
<div className="App">
<h1>Projects</h1>
</div>
);
}
}
export default App;
React package.json:
{
"name": "my-full-stack-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:5000",
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [">0.2%", "not dead", "not op_mini all"],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Your server is running on port 5000 and the client on port 3000. So, you have to call the api request as
fetch('http://localhost:5000/api/projects/')
If you don't specify the full URL, the request will be sent to http://localhost:3000/api/projects
You can also store the base URL in a constant.
import React from 'react';
import './App.css';
const baseUrl = 'http://localhost:5000';
class App extends React.Component {
constructor() {
super();
this.state = {
projects: []
}
}
componentDidMount() {
fetch(`${baseUrl}/api/projects/`)
.then(res => res.json())
.then(projects => this.setState({ projects }, () => console.log('Projects fetched...', projects)));
}
render() {
return (
<div className="App">
<h1>Projects</h1>
</div>
);
}
}
export default App;
Seems it was a cross-origin request. I installed the cors middleware, following the steps in the expressjs documentation, and added it to my express file and used app.use(cors()). Everything works now!
Just throwing this in, I know this has been answered, but I encountered this problem and was spinning my wheels for a while on it, despite all the solutions. Here is how I figured out to make it work:
I was a bit confused about the ports to use, as the app opens in port 3000, even though I had specified 5000 for my Express server. So I changed all ports everywhere to 3000 to try it out.
then I restarted my server first, then my react app, and it asked me if I wanted to open it on another port because 3000 was already being used. I said yes, and viola, it works. It now opens on port 3001 and everything works beautifully.
Code below to help any who may come to this page later, like I did.
server.js (express):
const express = require('express');
const cors = require('cors');
const knex = require('knex');
const db = knex({
client: 'pg',
connection: {
host: "127.0.0.1",
user: "",
password: "",
database: "",
},
});
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// CORS implemented so that we don't get errors when trying to access the server from a different server location
app.use(cors());
// GET: Fetch all movies from the database
app.get('/', (req, res) => {
db.select('*')
.from('cards')
.then((data) => {
console.log(data);
res.json(data);
})
.catch((err) => {
console.log(err);
});
});
const port = 3000;
app.listen(port, () => console.log(`Server running on port ${port}, http://localhost:${port}`));
React App.js:
import React, { useState, useEffect } from 'react';
import './App.css';
const App = () => {
useEffect(() => {
const getAPI = () => {
const API = 'http://127.0.0.1:3000';
fetch(API)
.then((response) => {
console.log(response);
return response.json();
})
.then((data) => {
console.log(data);
setLoading(false);
setApiData(data);
});
};
getAPI();
}, []);
const [apiData, setApiData] = useState([]);
const [loading, setLoading] = useState(true);
return (
..... react stuff here .....
);
};
export default App;
I successfully ran MERN app in my local machine using docker. Then, just for fun, I wanted it to deply to AWS, EC2 instance. After deploying, the fetch call in react-app gives this error:
GET http://localhost:5000/posts/ net::ERR_CONNECTION_REFUSED
App.js:37 TypeError: Failed to fetch
I am just creating and getting posts from react app which gets saved in mongodb. This works well in the local machine but not in the Amazon EC2 instance(Ubuntu 18.04), it doesn't work even though the frontend part is still showing but gives error when there is a api call.
I sshed the instance and tried curl command inside it, it gave the correct result. But using public url provided, i.e, from react app, gives above error.
Here are some details and hope you guys can help me.
React: App.js
import React from 'react';
import './App.css';
const serverUrl = 'http://localhost:5000'
const postModel = {
title: '',
body: '',
}
function App() {
const [posts, setPosts] = React.useState([])
const [post, setPost] = React.useState({ ...postModel })
React.useEffect(() => {
//get all the posts
fetch(`${serverUrl}`, {
method: 'GET',
})
.then(res => res.json())
.then(res => {
console.log(res)
})
.catch(err => console.log(err))
//get all the posts
fetch(`${serverUrl}/posts/`, {
method: 'GET',
})
.then(res => res.json())
.then(res => {
setPosts([...res])
})
.catch(err => console.log(err))
}, [])
const _postChange = (e) => {
setPost({ ...post, [e.target.name]: e.target.value })
}
const _addPost = () => {
//add new post
const requestJson = JSON.stringify(post)
console.log(requestJson)
fetch(`${serverUrl}/post/add/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: requestJson
})
.then(res => res.json())
.then(res => {
console.log(res)
setPosts([...posts, { title: res.post.title, body: res.post.body }]);
setPost({ ...postModel })
})
.catch(err => console.log(err))
}
console.log(post)
return (
<div className="App">
<h2>All Posts</h2>
<div>
<input placeholder="Post Title" value={post.title} onChange={_postChange} type="text" name="title" />
<input placeholder="Post body" value={post.body} onChange={_postChange} name="body" />
<button onClick={_addPost}>Add</button>
</div>
<div>
{posts.map((instance, index) => {
return <div key={index}>
<h4>{instance.title}</h4>
<p>{instance.body}</p>
<hr />
</div>
})}
</div>
</div>
);
}
export default App;
React: Dockerfile
# build environment
FROM node:12.2.0-alpine as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package.json /app/package.json
RUN npm install --silent
RUN npm install react-scripts#3.4.1 -g --silent
COPY . /app
RUN npm run build
# production environment
FROM nginx:1.16.0-alpine
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
React: package.json
{
"name": "react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"cra-template": "1.0.3",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
backend: index.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Post = require('./models/Post');
const cors = require('cors')
const app = express();
app.use(cors());
app.use(bodyParser.json());
// Connect to MongoDB
mongoose
.connect(
'mongodb://mongo:27017/node-mongo-docker',
{ useNewUrlParser: true }
)
.then(() => console.log('MongoDB is on'))
.catch(err => console.log(err));
//test the work
app.get('/', (req, res) => {
res.json({ 'message': 'Working properly' })
})
//get all posts
app.get('/posts', (req, res) => {
console.log("Getting of posts")
Post
.find()
.then(posts => res.json(posts))
.catch(err => res.json({ 'error': err }))
})
//post a new post
app.post('/post/add', (req, res) => {
console.log(req.body)
const newPost = new Post({
title: req.body.title,
body: req.body.body,
})
newPost
.save()
.then(post => res.json({ 'post': post }))
});
const port = 5000;
app.listen(port, () => console.log('Server is on'));
backend: Dockerfile
FROM node:12.2.0-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 5000
CMD ["npm", "start"]
backend: package.json
{
"name": "node-mongo-docker",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"cors": "^2.8.5",
"express": "^4.16.3",
"mongoose": "^5.2.7",
"nodemon": "^2.0.4"
}
}
docker-compose.yml
version: '3'
services:
react:
container_name: react-app
build: ./react-app
ports:
- '80:80'
links:
- server
server:
container_name: node-mongo-docker
restart: always
build: ./node-mongo
ports:
- '5000:5000'
links:
- mongo
# volumes:
# - '.:/usr/src/app'
mongo:
container_name: mongo
image: mongo
ports:
- '27017:27017'
You will need to replace "localhost" with the url of the deployed back-end.
React is a client-side javascript library, and runs in the users web browser, so it will use the "localhost" of the user that visits your page, not the server's localhost.