users.js私は、ユーザー名がデータベースに存在し、応答コードを送信することは200/400
import express from 'express'
import Validator from 'validator'
import isEmpty from 'lodash/isEmpty'
import isEmail from 'validator/lib/isEmail';
import {MongoClient} from 'mongodb'
let router = express.Router()
function validatInput(data){
var error = {}
if(data.username === ""){
error.email = "this field is req"
}
if(!isEmail(data.username)){
error.email = "email is not valid "
}
if(data.password === ""){
error.password = "this field is req"
}
return{
error:error,
isValid:isEmpty(error)
}
}
router.post('/',(reqs,resP)=>{
var url ="mongodb://localhost:27017/loginUsers"
const {error,isValid} = validatInput(reqs.body)
error.email = err
console.log(error.email +"body")
if(!isValid){
console.log("not valid")
resP.status(400).send(error)
}
let err=""
MongoClient.connect(url,function (err,db) {
if(err){
console.log("database connection error")
}
else{
var collection = db.collection('UsersList')
var student = reqs.body
console.log(" email "+ reqs.body.username)
collection.find({"username":reqs.body.username},function(err,res){
if(err){
console.log(err)
}
else if(!res){
err=null
console.log(" not find")
collection.insert([student],function(err,res){
if(err){
console.log("data not inserted")
}else{
console.log(res)
}
})
resP.status("success")
}
else{
console.log("usere present")
error.email = "email is not valid "
resP.status(400).send(error)
}
})
}
})
})
export default router
場合は、フィールド内のデータが有効であるかどうか、それは最初にチェックし、データベースが同じユーザ名を持っているかどうかを確認またはチェックしています フィールドが正しい/間違っている場合は成功します しかし、(非同期動作のために)データベースを確認すると待機しません。そして、私はクロームでネットワークをチェックし、そのことはMongoDBの中でチェックした後、私は唯一の
データを送信できるように、この問題 を解決するためにどのようにusers.jsの保留状態を示しserver.jsと 常に200のステータスを送信するために行きます
index.js
import express from 'express';
import webpack from 'webpack';
import path from 'path';
import config from '../webpack.config.dev';
import open from 'open';
import bodyparser from 'body-parser'
import users from './routes/users'
/* eslint-disable no-console */
const port = 3000;
const app = express();
const compiler = webpack(config);
app.use(bodyparser.json())
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.use('/api/users',users)
app.get('*', function(req, res) {
console.log("i am sending file")
res.sendFile(path.join(__dirname, '../src/index.html'));
});
app.listen(port, function(err) {
if (err) {
console.log(err);
} else {
open(`http://localhost:${port}`);
}
});
を動作するかどうか、私に教えてください? – Deep
"StackOverFlow"が私に提案しました。 –
okkayありがとう、私は道がある。 –