curl:(52)来自服务器的空回复发帖后无回复

时间:2019-06-04 22:02:53

标签: javascript node.js

我正在尝试使用JWT设置身份验证,并且尝试使用curl或邮递员发送电子邮件和密码时,服务器使我挂起并且什么也不做。

试图修复app.js

这是我的登录路线

const User = require('../../jwtAuth/models/Login.js');
// POST route to register a user
var express = require("express");
var router = express.Router();
router.post('/api/register', function (req, res) {
    const {
        email,
        password
    } = req.body;
    const user = new User({
        email,
        password
    });
    console.log(user);
    user.save(function (err) {
        console.log('teste2');
        if (err) {
            console.log(err);
            res.status(500)
                .send("Error registering new user please try again.");
        } else {
            res.status(200).send("Welcome to the club!");
        }
    });
});




module.exports = router;

这是一些中间件

const secret = "abc";
const jwt = require('jsonwebtoken');
const withAuth = function (req, res, next) {
    const token =
        req.body.token ||
        req.query.token ||
        req.headers['x-access-token'] ||
        req.cookies.token;
    if (!token) {
        res.status(401).send('Unauthorized: No token provided');
    } else {
        jwt.verify(token, secret, function (err, decoded) {
            if (err) {
                res.status(401).send('Unauthorized: Invalid token');
            } else {
                req.email = decoded.email;
                next();
            }
        });
    }
}
module.exports = withAuth;

这是我的模特

// User.js
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const saltRounds = 10;
const UserSchema = new mongoose.Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    }
});
console.log('teste');
UserSchema.pre('save', function (next) {
    console.log('teste1');

    // Check if document is new or a new password has been set
    if (this.isNew || this.isModified('password')) {
        console.log('teste2');

        // Saving reference to this because of changing scopes
        const document = this;
        //console.log(document);
        bcrypt.hash(document.password, saltRounds,
            function (err, hashedPassword) {
                //console.log(err);
                console.log(hashedPassword);
                if (err) {
                    next(err);
                } else {
                    document.password = hashedPassword;
                    next();
                }
            });
    } else {
        next();
    }
});

module.exports = mongoose.model('User', UserSchema);

这是我的app.js

var cors = require('cors');
var mongoose = require('mongoose');
var expressGraphQL = require('express-graphql');
var bodyParser = require('body-parser');
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cookieParser = require('cookie-parser');

var withAuthRouter = require('./src/api/jwtAuth/middleware/middleware');
var indexRouter = require('./src/api/routes/index');
var usersRouter = require('./src/api/routes/users');
var issuesRouter = require('./src/api/routes/issues');
var emailRouter = require('./src/api/routes/email');
var loginRouter = require('./src/api/jwtAuth/routes/login');
var authRouter = require('./src/api/jwtAuth/routes/auth');


var app = express();
require('dotenv').config();
console.log(process.env.SECRET);

app.use(
  cors(),
  bodyParser.json()
)

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/issues', issuesRouter);
app.use('/email', emailRouter);
app.use('/', loginRouter);
app.use('/auth', authRouter);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

//jwt
app.get('/api/secret', withAuthRouter, function (req, res) {
  res.send('The password is ');
});

app.get('/checkToken', withAuthRouter, function (req, res) {
  res.sendStatus(200);
});

module.exports = app;

有人可以帮助我吗?我昨天有这个工作,但是我更改了文件夹结构,为带有模型,路由器和中间件的jwt东西创建了一个文件夹,并且可能更改了app.js上的内容,但是它停止了工作。如果需要,我还可以给github链接,我不知道如何解决它。

[nodemon] starting `node ./bin/www`
teste
webapp
Port: 3000 running
{ _id: 5cf6cad96c07bb2cbd877865,
  email: 'admin@me.com',
  password: 'admin' }
teste1
teste2
$2a$10$LE9mgMahfRNO2TkTbPAC9ONB215jpURxQAuCgmErjDbriI6P9tOna
POST /api/register - - ms - -```

this is what i get from my console.logs. Mongo is up and running.

0 个答案:

没有答案