var Express = require('Express');
var bodyParser = require('body-parser');
var Cors = require('cors');
var router = Express.Router();
var UserRoute = require('./route');
var app = Express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(Cors());
app.use('/', UserRoute);
app.listen('8081', '127.0.0.1', function(err) {
if(err) {
console.log(err);
process.exit(-1);
}
console.log("Server listen on port 8081");
})
...............................................................//
const Express=require("express");
var Routes= Express.Router();//to handle routes
var UserRoute=require('./UserController/User.Route');
Routes.use('/user/',UserRoute);
module.exports=Routes;//use to export variables
..............................................................//
var express = require('express');
var router = express.Router();
var controller = require('./user.controller');
router.post('/', (req, res) => {
controller.add(req.body).then(response => {
res.status(response.status).send(response.message);
}).catch(err => {
res.status(err.status).send(err.message);
})
});
router.get('/', (req, res) => {
controller.getAll().then(response => {
res.status(response.status).send(response);
}).catch(err => {
res.status(err.status).send(err.message);
})
});
router.get('/:id', (req, res) => {
controller.getSingle(req.params.id).then(response => {
res.status(response.status).send(response);
}).catch(err => {
res.status(err.status).send(err.message);
})
});
router.put('/:id', (req, res) => {
controller.update(req.params.id, req.body).then(response => {
res.status(response.status).send(response);
}).catch(err => {
res.status(err.status).send(err.message);
})
});
router.delete('/:id', (req, res) => {
controller.delete(req.params.id).then(response => {
res.status(response.status).send(response);
}).catch(err => {
res.status(err.status).send(err.message);
})
})
module.exports = router;
...........................................................................//
var mongoose = require('../DBschema');
var UserSchema = mongoose.model('User');
var UserController = function() {
this.add = function(userInstance) {
return new Promise((resolve, reject) => {
var user = new UserSchema({
name: userInstance.name
})
user.save().then(() => {
resolve({'status': 200, 'message':'added new user'});
}).catch(err => {
reject({'status': 404, 'message':'err:-'+err});
})
})
}
this.getAll = function() {
return new Promise((resolve, reject) => {
UserSchema.find().exec().then(data => {
resolve({'status': 200, 'message':'get all data', 'data': data});
}).catch(err => {
reject({'status': 404, 'message':'err:-'+err});
})
})
}
this.getSingle = function(id) {
return new Promise((resolve, reject) => {
UserSchema.find({_id: id}).exec().then(data => {
resolve({'status': 200, 'message':'get single data', 'data': data});
}).catch(err => {
reject({'status': 404, 'message':'err:-'+err});
})
})
}
this.update = function(id, updateData) {
return new Promise((resolve, reject) => {
UserSchema.update({_id: id}, updateData).then(() => {
resolve({'status': 200, 'message':'update user'});
}).catch(err => {
reject({'status': 404, 'message':'err:-'+err});
})
})
}
this.delete = function(id) {
return new Promise((resolve, reject) => {
UserSchema.remove({_id: id}).then(() => {
resolve({'status': 200, 'message':'delete user'});
}).catch(err => {
reject({'status': 404, 'message':'err:-'+err});
})
})
}
}
module.exports = new UserController();
......................................................................//
//all the schemas are there
var mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name:{
type:String,
require:true
},
address:{
type:String,
require:false
},
password:{
type:String,
require:true
}
});
mongoose.model('User',UserSchema);//(name of a schema,custom schema tht u created)
mongoose.connect('mongodb://127.0.0.1:27017/demo',function (err) {
if(err){
console.log(err);
process.exit(-1);
}
else{
console.log("connected to the DB");
}
});//127.0.0.1 or localhost
module.exports=mongoose;//exporting mongoose
/*
//////////////////////////////////////////////////////////////
// Spingboot
// App.java
package SpringBootWithMongo.SpringBootWithMongo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
.....................................................................
User,model
package SpringBootWithMongo.SpringBootWithMongo.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="users")
public class User {
@Id
private String Id;
private String name;
public String getId() {
return Id;
public void setId(String id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
.........................................................................
UserRepository,model
package SpringBootWithMongo.SpringBootWithMongo.model;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends MongoRepository<User, String>{
}
..........................................................................
UserService,service
package SpringBootWithMongo.SpringBootWithMongo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import SpringBootWithMongo.SpringBootWithMongo.model.User;
import SpringBootWithMongo.SpringBootWithMongo.model.UserRepository;
@RestController
@RequestMapping("/")
public class UserService {
@Autowired
private UserRepository repository;
@RequestMapping(method = RequestMethod.POST)
public void AddUser(@RequestBody User instance) {
try {
repository.save(instance);
} catch(Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("finally")
@RequestMapping(method = RequestMethod.GET)
public List<User> GetAllUsers() {
List<User> userList = null;
try {
userList = repository.findAll();
} catch(Exception e) {
e.printStackTrace();
} finally {
return userList;
}
}
@SuppressWarnings("finally")
@RequestMapping(value = "/{Id}", method = RequestMethod.GET)
public User getSingle(@PathVariable String Id) {
User instance = null;
try {
instance = this.findOne(Id);
} catch(Exception e) {
e.printStackTrace();
} finally {
return instance;
}
}
@RequestMapping(value = "/{Id}", method = RequestMethod.PUT)
public void updateUser(@RequestBody User instance, @PathVariable String Id) {
try {
User updateInstance = this.findOne(Id);
updateInstance.setName(instance.getName());
repository.save(updateInstance);
} catch(Exception e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/{Id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable String Id) {
try {
repository.delete(this.findOne(Id));
} catch(Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("finally")
private User findOne(String Id) {
User instance = null;
try {
List<User> userList = repository.findAll();
for(User user: userList) {
if(user.getId().equals(Id)) {
instance = user;
break;
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
return instance;
}
}
}
*/............................................................................................
/*application.properties
server.port=8083
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=user_demo`enter code here`*/
我需要知道这是单页web应用程序中后端的代码是正确的。这些用于实现网页的后端我已经使用了nodejs和Springboot来实现这个代码请检查这些是正确的还是不。 首先,我实现了nodejs代码 我一步一步地添加了我的代码 mongodb用于此网站db 在nodejs代码之后,我实现了Springboot,这两个代码都用于实现网站的后端