我对NodeJS很陌生,我尝试在这里查看已接受的答案,做了一些挖掘,但在下面的具体例子中找不到任何具体原因。任何想法,有什么可能是错的?我只知道与res有关。
我还怀疑我get
html file
的方式与products
db
的方式之间可能存在干扰?
我的server.js:
var http = require('http')
var express = require('express')
var app = express()
server = http.createServer(app)
var formidable = require('express-formidable');
app.use(formidable());
app.use(express.static(__dirname + '/public'));
var fs = require('fs')
var path = require('path');
var mongo = require('mongodb').MongoClient
global.db = null
var sDatabasePath = 'mongodb://localhost:27017/webshop'
global.mongoId = require('mongodb').ObjectID
/**************************************************/
var user = require(path.join(__dirname + '/user.js'))
/**************************************************/
app.get('/shopaholic', (req, res) => { res.sendFile(path.join(__dirname + '/shopaholic.html')) })
mongo.connect(sDatabasePath, (err, db) => {
if (err) {
console.log('ERROR 003 -> Cannot connect to the database')
return false
}
global.db = db
console.log('OK 002 -> Connected to the database')
return true
})
/**************************************************/
app.post('/save-user', (req, res) => {
user.saveUser(req.fields, (err, jResult) => {
if (err) {
console.log(jResult)
return res.send('ERROR')
}
console.log(jResult)
return res.send('OK')
})
})
/**************************************************/
app.get('/products', (req, res) => {
user.getProducts((err, ajUsers) => {
if (err) {
return res.send('ERROR')
}
console.log(ajUsers)
return res.send(ajUsers)
})
})
app.listen(3000, (err) => {
if (err) {
console.log('ERROR 001 -> Cannot listen to port 3000')
return false
}
console.log('OK 000 -> Server listening to port 3000')
})
我的user.js:
var user = {}
/**************************************************/
user.getProducts = (fCallback) => {
// get the data from the collection users
global.db.collection('products').find().toArray((err, ajUsers) => {
if (err) {
var jError = { "status": "error", "message": "ERROR -> user.js -> 001" }
console.log(jError)
return fcallback(true, jError)
}
console.log("ajUsers", ajUsers);
return fCallback(false, ajUsers)
})
}
/**************************************************/
user.saveUser = (jUserData, fcallback) => {
var jUser = { "userName": jUserData.txtEmailorPhoneNumber, "firstName": jUserData.txtName, "lastName": jUserData.txtLastName, "password": jUserData.txtPassword, "image": jUserData.imgPath }
global.db.collection('users').insertOne(jUser, (err, jResult) => {
if (err) {
var jError = { "status": "error", "message": "ERROR -> user.js -> 001" }
console.log(jError)
return fcallback(true, jError)
}
var jOk = { "status": "ok", "message": "user.js -> saved -> 000" }
console.log(jOk)
return fcallback(false, jOk)
})
}
/**************************************************/
module.exports = user
前端的JAVACRIPT(shopaholic.html):
btnSignupForm.addEventListener("click", signupUser);
function signupUser() {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var ajUserDataFromServer = JSON.parse(this.responseText);
//console.log( "Response:" + ajUserDataFromServer );
if (ajUserDataFromServer.status == "ok") {
//console.log( "SIGNUP SUCCESFULL" );
pageLogin.style.display = "flex";
lblLoginErrorMessage.innerHTML = "";
var sSignupSeuccesMessage = "Account succesfully created - Signup please";
var sSignupSeuccesMessage = sSignupSeuccesMessage.fontcolor("#549839");
lblLoginErrorMessage.insertAdjacentHTML('beforeend', sSignupSeuccesMessage);
} else {
//console.log( "SIGNUP FAIL - TRY AGAIN" );
pageViewProducts.style.display = "none";
pageSignup.style.display = "flex";
lblSignupErrorMessage.innerHTML = "";
var sSignupErrorMessage = "Signup Failed - Try again";
lblSignupErrorMessage.insertAdjacentHTML('beforeend', sSignupErrorMessage);
}
}
}
request.open("POST", "/save-user", true);
var jFrmSignup = new FormData(frmSignup);
request.send(jFrmSignup);
}
function getajProductData() {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
ajProductDataFromServer = JSON.parse(this.responseText);
//console.log( "Response:" + ajProductDataFromServer );
if (sessionStorage.getItem('role') === "admin") {
//console.log( "PRODUCTS ARE EDITABLE" );
showProductAdmin();
} else if (sessionStorage.getItem('role') === "user") {
//console.log( "PRODUCTS ARE AVAILABLE FOR USER" );
showProduct();
} else {
//console.log( "PRODUCTS AVAILABLE FOR PUBLIC" );
showProduct();
}
}
}
request.open("GET", "/products", true);
request.send();
}