Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Import React and the stylesheet.
import React from 'react';
import './App.css';

// Import the component to be used for fetching, posting,
// and displaying messages from the server.
import Messages from './Messages';

// Initialize the application display, giving a
// placeholder for the Messages component.
function App() {
return (
<div className="App">
<Messages />
</div>
);
}

export default App;
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Import React's Component and Axios.
import React, { Component } from 'react';
import axios from 'axios';

// Create the component for handling messages.
class Messages extends Component {
// Create an object to hold the list of messages and the message
// being prepared for sending.
state = {
list: [],
toSend: ""
};

// When the component loads, get existing messages from the server.
componentDidMount() {
this.fetchMessages();
}

// Get messages from the server.
fetchMessages = () => {
axios
.get('/messages')
.then((res) => {
if (res.data) {
this.setState({ list: res.data, toSend: "" });
let inputField = document.getElementById("textInputField");
inputField.value = "";
} else {
this.setState({ list: ["No messages!"] });
}
})
.catch((err) => console.log(err));
}

// Post new messages to the server, and make a call to update
// the list of messages.
sendMessage = () => {
if (this.state.toSend === "") {
console.log("Enter message text.")
} else {
axios
.post('/messages', { messageText: this.state.toSend })
.then((res) => {
if (res.data) {
this.fetchMessages();
}
})
.catch((err) => console.log(err));
}
}

// Display the list of messages.
listMessages = () => {
if (this.state.list && this.state.list.length > 0) {
return (this.state.list.map((message) => {
return (
<p>{message.messageText}</p>
);
}))
} else {
return (<p>No messages!</p>)
}
}

// Render the message component.
render() {
return (
<div>
<div>
<input id="textInputField" type="text" onChange={ (e) => { this.setState({ toSend: e.target.value }) } } />
<button onClick={this.sendMessage}>Send Message</button>
</div>
<div>{ this.listMessages() }</div>
</div>
);
}
}

export default Messages;
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Set up ExpressJS.
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
const port = 5000;

// Set up Mongoose.
const mongoose = require('mongoose');
const mongoDbUrl = 'mongodb://127.0.0.1/example_database';

// Import MongoDB models.
const MessageModel = require('./models/message.js');

// Connect to the database.
mongoose
.connect(mongoDbUrl, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('Database connection established.'))
.catch((err) => console.log('Database connection error: ' + err))
mongoose.Promise = global.Promise;

// Prevent possible cross-origin issues.
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});

// Necessary to handle the JSON data.
app.use(bodyParser.json());

// Create endpoints for the frontend to access.
app.get('/messages', (req, res, next) => {
MessageModel
.find({}, 'messageText')
.then((data) => res.json(data))
.catch(next);
});

app.post('/messages', (req, res, next) => {
if (req.body.messageText) {
MessageModel.create(req.body)
.then((data) => res.json(data))
.catch(next);
} else {
res.json({error: "Please provide message text."});
}
});

// Listen on the port.
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});

Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Set up Mongoose.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create a schema to be used for the MessageModel.
const MessageSchema = new Schema({
messageText: {
type: String,
required: [true, 'This fields is required.'],
},
});

// Create the message model from the MessageSchema.
const MessageModel = mongoose.model('message', MessageSchema);

module.exports = MessageModel;
Loading