javascript 实时MERN CRUD DOCKER
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 实时MERN CRUD DOCKER相关的知识,希望对你有一定的参考价值。
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const socket = require('socket.io');
const config = require('./config/db');
// Use Node's default promise instead of Mongoose's promise library
mongoose.Promise = global.Promise;
// Connect to the database
mongoose.connect(config.db);
let db = mongoose.connection;
db.on('open', () => {
console.log('Connected to the database.');
});
db.on('error', (err) => {
console.log(`Database error: ${err}`);
});
// Instantiate express
const app = express();
// Don't touch this if you don't know it
// We are using this for the express-rate-limit middleware
// See: https://github.com/nfriedly/express-rate-limit
app.enable('trust proxy');
// Set public folder using built-in express.static middleware
app.use(express.static('public'));
// Set body parser middleware
app.use(bodyParser.json());
// Enable cross-origin access through the CORS middleware
// NOTICE: For React development server only!
if (process.env.CORS) {
app.use(cors());
}
// Initialize routes middleware
app.use('/api/users', require('./routes/users'));
app.use('/api/employees', require('./routes/employees'));
// Use express's default error handling middleware
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
res.status(400).json({ err: err });
});
// Start the server
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
// Set up socket.io
const io = socket(server);
let online = 0;
io.on('connection', (socket) => {
online++;
console.log(`Socket ${socket.id} connected.`);
console.log(`Online: ${online}`);
io.emit('visitor enters', online);
var tm = + new Date();
io.emit('m1', tm);
io.emit('m2', "this is m2");
socket.on('add', data => socket.broadcast.emit('add', data));
socket.on('update', data => socket.broadcast.emit('update', data));
socket.on('delete', data => socket.broadcast.emit('delete', data));
socket.on('disconnect', () => {
online--;
console.log(`Socket ${socket.id} disconnected.`);
console.log(`Online: ${online}`);
io.emit('visitor exits', online);
});
});
// expressjs mongoose router
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Employee = require('../models/employee');
router.get('/:id', (req, res) => {
Employee.findById(req.params.id)
.then((result) => {
res.json(result);
})
.catch((err) => {
res.status(404).json({ success: false, msg: `No such employee.` });
});
});
router.get('/', (req, res) => {
console.log("this is get all")
Employee.find({})
.then((result) => {
res.json(result);
})
.catch((err) => {
res.status(500).json({ success: false, msg: `Something went wrong. ${err}` });
});
});
router.post('/', (req, res) => {
let newEmployee = new Employee({
name: req.body.name,
email: req.body.email,
age: req.body.age,
gender: req.body.gender,
gl: "01/01",
});
newEmployee.save()
.then((result) => {
res.json({
success: true,
msg: `Successfully added!`,
result: {
_id: result._id,
name: result.name,
email: result.email,
age: result.age,
gender: result.gender,
//gl: result.gl,
}
});
})
.catch((err) => {
if (err.errors) {
res.status(500).json({ success: false, msg: `Something went wrong. ${err}` });
}
});
});
module.exports = router;
// express mongoose model
const mongoose = require('mongoose');
const EmployeeSchema = new mongoose.Schema({
name: {
type: String,
},
email: {
type: String,
},
age: {
type: Number,
},
gender: {
type: String,
}
});
const Employee = module.exports = mongoose.model('employee', EmployeeSchema);
import React, { Component } from 'react';
import axios from 'axios';
import io from 'socket.io-client';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
import Button from 'material-ui/Button';
import Select from 'material-ui/Select';
import { MenuItem } from 'material-ui/Menu';
import { FormControl, FormHelperText } from 'material-ui/Form';
import Input, { InputLabel } from 'material-ui/Input';
const p1 = {margin: 10, padding: 10, width: 400, height: 300}
export default class Socket1 extends Component {
constructor() {
super();
this.server = process.env.REACT_APP_API_URL || '';
this.socket = io.connect(this.server);
this.state = {
users: [],
online: 0,
m1: 0,
name: 'Mannir',
age: '',
email: '',
gender: '',
}
this.fetchUsers = this.fetchUsers.bind(this);
this.fetchEmployees = this.fetchEmployees.bind(this);
this.handleUserAdded = this.handleUserAdded.bind(this);
this.handleEmployeeAdded = this.handleEmployeeAdded.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
var tm = + new Date();
this.fetchUsers();
this.fetchEmployees();
this.socket.on('visitor enters', data => this.setState({ online: data }));
this.socket.on('visitor exits', data => this.setState({ online: data }));
//this.socket.on('add', data => this.handleUserAdded(data));
this.socket.on('add', data => this.handleEmployeeAdded(data));
this.socket.on('m2', data => {
console.log("Scoket1::this.socket.on('m2'::data="+data)
});
}
fetchUsers() {
axios.get(`${this.server}/api/users/`)
.then((response) => {
this.setState({ users: response.data });
})
.catch((err) => {
console.log(err);
});
}
fetchEmployees() {
axios.get(`${this.server}/api/employees/`)
.then((response) => {
this.setState({ employees: response.data });
})
.catch((err) => {
console.log(err);
});
}
handleUserAdded(user) {
let users = this.state.users.slice();
users.push(user);
this.setState({ users: users });
}
handleEmployeeAdded(employee) {
let employees = this.state.employees.slice();
employees.push(employee);
this.setState({ employees: employees });
}
handleChange1 = (e) => {
this.setState({[e.target.name]: e.target.value});
}
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
handleTest1 = (e) => {
console.log("handleTest1 clicked")
}
handleSubmit1 = (e, v) => {
var time = (new Date).getTime();
console.log(time)
console.log(v)
/*
axios.get(`${this.server}/api/users/`)
.then((response) => {
//this.setState({ users: response.data });
console.log(response.data)
})
.catch((err) => {
console.log(err);
});
*/
var emp = {
name: "Employee 1",
email: "employee1@m.com",
age: 21,
gender: "M",
gl: "01/01"
}
this.handleEmployeeAdded(emp);
}
handleSubmit(e, v) {
// Prevent browser refresh
e.preventDefault();
const user = {
name: 'name1',// this.state.name,
email: '1@m.com',//this.state.email,
age: 20, //this.state.age,
gender: 'M',// this.state.gender
}
// Acknowledge that if the user id is provided, we're updating via PUT
// Otherwise, we're creating a new data via POST
const method = 'post';// this.props.userID ? 'put' : 'post';
const params = ''; // this.props.userID ? this.props.userID : '';
axios({
method: method,
responseType: 'json',
url: `${this.server}/api/employees/${params}`,
data: user
})
.then((response) => {
this.setState({
formClassName: 'success',
formSuccessMessage: response.data.msg
});
if (!this.props.userID) {
this.setState({
name: '',
email: '',
age: '',
gender: ''
});
this.props.onUserAdded(response.data.result);
this.props.socket.emit('add', response.data.result);
}
else {
this.props.onUserUpdated(response.data.result);
this.props.socket.emit('update', response.data.result);
}
})
.catch((err) => {
if (err.response) {
if (err.response.data) {
this.setState({
formClassName: 'warning',
formErrorMessage: err.response.data.msg
});
}
}
else {
this.setState({
formClassName: 'warning',
formErrorMessage: 'Something went wrong. ' + err
});
}
});
}
render() {
console.log(this.state.employees)
let online = this.state.online;
let verb = (online <= 1) ? 'is' : 'are'; // linking verb, if you'd prefer
let noun = (online <= 1) ? 'person' : 'people';
return (
<div>
<Paper style={p1} elevation={4}>
<h3>Employee Form</h3>
<FormControl style={{margin: 10}}>
<InputLabel htmlFor="gender-simple">Age</InputLabel>
<Select
value={this.state.gender}
onChange={this.handleChange}
inputProps={{
name: 'gender',
id: 'gender-simple',
}}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem value={'M'}>Male</MenuItem>
<MenuItem value={'F'}>Female</MenuItem>
</Select>
</FormControl>
<TextField
id="name"
label="Name"
style={{width: 200}}
value={this.state.name}
margin="normal"
/>
<br />
<Button variant="raised" color="primary" style={{margin: 10}} onClick={(e)=>{this.handleSubmit(e, "add")}}>Add</Button>
<Button variant="raised" color="secondary" className={{margin: 10}} onClick={(e)=>{this.handleSubmit(e, "remove")}}>Remove</Button>
<br /><br />
{+ new Date()}
<br />
<em id='online'>{`${online} ${noun} ${verb} online.`}</em>
</Paper>
</div>
);
}
}
FROM node:latest
RUN mkdir -p /usr/src/app/react-src
WORKDIR /usr/src/app
RUN npm install -g nodemon
COPY package.json /usr/src/app/
RUN npm install
COPY react-src/package.json /usr/src/app/react-src
RUN npm install
COPY . /usr/src/app
EXPOSE 3000 4200
import React, { Component } from 'react';
import axios from 'axios';
import io from 'socket.io-client';
import Paper1 from './Paper1'
import Socket1 from './Socket1'
class App extends Component {
constructor() {
super();
}
componentDidMount() {
//
}
render() {
return (
<div><Socket1 /></div>
);
}
}
export default App;
以上是关于javascript 实时MERN CRUD DOCKER的主要内容,如果未能解决你的问题,请参考以下文章
使用 mern 堆栈和 socket.io 的聊天应用程序在发送超过 20 条消息后变慢
是否有任何用于 Laravel 包的 Backpack 允许实时 AJAX CRUD 编辑?
HBase 数据库系统可以用作具有 CRUD 功能的实时应用程序数据库吗?