weixin_33701251 2016-10-26 21:04 采纳率: 0%
浏览 12

带有ajax,jquery的POST json

I need to login on my rest service. I parse the json and the data seems correct. But it doesn't work.

First I load the form data with the names: 'username' and 'wachtwoord' Then I parse it to a json, and send it to my rest service. But every time it fails.

POST request

$(document).ready(function() {
    $('#doLogin').submit(function() {
        var $inputs = $('#doLogin :input');

        var values = {};
        $inputs.each(function() {
            values[this.name] = $(this).val();
        });
        var data = {}
        var Form = this;

        //Gathering the Data
        //and removing undefined keys(buttons)
        $.each(this.elements, function(i, v){
            var input = $(v);
            data[input.attr("name")] = input.val();
            delete data["undefined"];
        });

        $.ajax({
            cache: false,
            url : "http://localhost:666/api/login/",
            type: "POST",
            dataType : "json",
            data: JSON.stringify(data),
        }).fail(function (jqXHR, textStatus) {
            alert("Login Failed");
        }).done(function (data) {
            alert(data.token);
        });
    });
});

REST server

var jwt = require('jsonwebtoken');
var express = require('express');
var router = express.Router();
var User = require('./model/users');

var privateKey = "1fjdu89379edfasf73";

router.post('/', function (req, res) {
    var name = req.body.username;
    var pass = req.body.wachtwoord;
    User.findOne({username: name, wachtwoord: pass},

        function (err, user) {
            if (user) {
                var username = req.body.username;
                var token = jwt.sign({username: username}, privateKey, {expiresIn: 60 * 60 * 24});
                res.status(200).json({token: token});
            } else {
                res.status(500).json("Username or Password incorrect!");
            }
        });


});

module.exports = router;

</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
    • ¥15 这种微信登录授权 谁可以做啊
    • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
    • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
    • ¥15 网络设备配置与管理这个该怎么弄
    • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
    • ¥20 西门子S7-Graph,S7-300,梯形图
    • ¥50 用易语言http 访问不了网页
    • ¥50 safari浏览器fetch提交数据后数据丢失问题
    • ¥15 matlab不知道怎么改,求解答!!