快速路由在单页Web应用程序

时间:2017-03-02 18:05:23

标签: javascript jquery ajax node.js express

我正在将旧的LAMP堆栈项目转换为使用Node / Express / MongoDB而不是PHP / Laravel / MySQL。我像在Laravel一样建造了我的路线,并测试了我使用Postman建造的路线。通过Postman中的测试,每条路线都能正常工作。

但是,当我尝试在我编写的display.js文件中使用这些路由时,唯一有效的路由是GET / player。我正在寻找对这些路线以及我正在使用的显示文件的一些见解。

当我点击编辑按钮时,我的GET / player /:id路由会获取正确的信息(状态代码200和预览显示JSON对象),但不会填充表单中的字段。

当我点击删除按钮时,我得到404状态代码,响应为"无法获取/播放/ 123 /删除"。如何调整显示代码以使用DELETE而不是GET? (我相信如果我能弄清楚如何在display.js代码中传递请求方法,我可以使用正确的http请求方法将我的所有路由重构为/ players /:id)。

当我尝试提交新记录时,我收到400状态代码,其中包含验证错误,指出路径age是必需的。对于每个字段名称,它实际上是相同的错误,因此我假设我没有正确地将字段中的值传递给JSON对象。

我还没有能够测试补丁,但相信它应该通过修复DELETE / players /:id和GET / players /:id来解决。

感谢任何帮助。代码如下所示,用于显示和服务器js文件。

display.js

// this is the base url to which all your requests will be made
var baseURL = window.location.origin;
$(document).ready(function(){
// $.ajaxSetup({
//     headers: {
//         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
//     }
// });
$('#table').click(function(event) { // generates the table
    // change the url parameters based on your API here
    // Using an JQuery AJAX GET request to get data form the server
    $.getJSON(baseURL+'/players', function(data) {
        generateTable(data, $('#container'));
    });
});

$('#form').click(function(event) {
    // creating an empty form
    generateForm(null, $('#container'));
});
// Handle table click event for delete
$('#container').on('click', '.delete', function(event) {
    var id = $(this).val();
    // change the url parameters based on your API here
    // remember to create delete functionality on the server side (Model and Controller)
    // Using an JQuery AJAX GET request to get data form the server
    $.getJSON(baseURL+"/players/"+id+"/delete", function(data) {
        //Generate table again after delete
        //change the url based on your API parameters here
        // Using an JQuery AJAX GET request to get data from the server
        $.getJSON(baseURL+'/players', function(data) {
            generateTable(data, $('#container'));
        });
    });
});

// Handle form submit event for both update & create
// if the ID_FIELD is present the server would update the database otherwise the server would create a record in the database
$('#container').on('submit', '#my-form', function(event) {
    var id = $('#id').val();
    console.log(id);
    if (id != "") {
        event.preventDefault();
        submitForm(baseURL+"/players/"+id+"/edit", $(this));
    } else {
        event.preventDefault();
        submitForm(baseURL+"/player", $(this));
    }
});

// Handle table click event for edit
// generates form with prefilled values
$('#container').on('click', '.edit', function(event) {
    // getting id to make the AJAX request
    var id = $(this).val();
    // change the url parameters based on your API here
    // Using an JQuery AJAX GET request to get data form the server
    $.getJSON(baseURL+'/players/'+id, function(data) {
        generateForm(data, $('#container'));
    });
});

// function to generate table
function generateTable(data, target) {
    clearContainer(target);
    //Change the table according to your data
    var tableHtml = '<table><thead><tr><th>Name</th><th>Age</th><th>Position</th><th>Team</th><th>Delete</th><th>Edit</th></tr></thead>';
    $.each(data, function(index, val) {
        tableHtml += '<tr><td>'+val.playername+'</td><td>'+val.age+'</td><td>'+val.position+'</td><td>'+val.team+'</td><td><button class="delete" value="'+val._id+'">Delete</button></td><td><button class="edit" value="'+val._id+'">Edit</button></td></tr>';
    });
    tableHtml += '</table>';
    $(target).append(tableHtml);
}

// function to generate form
function generateForm(data, target){
    clearContainer(target);
    //Change form according to your fields
    $(target).append('<form id="my-form"></form>');
    var innerForm = '<fieldset><legend>Player Form</legend><p><label>Player Name: </label>'+'<input type="hidden" name="id" id="id"/>'+'<input type="text" name="playername" id="playername" /></p>' + '<p><label>Age: </label><input type="text" name="age" id="age" /></p>'+ '<p><label>Hometown: </label><input type="text" name="city" id="city" />'+ ' ' + '<input type="text" name="country" id="country" /></p>' + '<p><label>Gender: </label><input type="text" name="gender" id="gender" /></p>'+ '<p><label>Handedness: </label><input type="text" name="handedness" id="handedness" /></p>'+ '<p><label>Broom: </label><input type="text" name="broom" id="broom" /></p>'+ '<p><label>Position: </label><input type="text" name="position" id="position" /></p>'+ '<p><label>Team: </label><input type="text" name="team" id="team" /></p>'+ '<p><label>Favorite Color: </label><input type="text" name="favoritecolor" id="favoritecolor" /></p>'+ '<p><label>Headshot: </label><input type="text" name="headshot" id="Headshot" /></p>'+ '<input type="submit"/>';
    $('#my-form').append(innerForm);
    //Change values according to your data
    if(data != null){
        $.each(data, function(index, val) {
            $('#id').val(val._id);
            $('#playername').val(val.playername);
            $('#age').val(val.age);
            $('#city').val(val.city);
            $('#country').val(val.country);
            $('#gender').val(val.gender);
            $('#handedness').val(val.handedness);
            $('#broom').val(val.broom);
            $('#position').val(val.position);
            $('#team').val(val.team);
            $('#favoritecolor').val(val.favoritecolor);
            $('#Headshot').val(val.headshot);
        });
    }
}

function submitForm(url, form){
    $.post(url, form.serialize(), function(data) {
        showNotification(data, $('#notification'));
    });
}

function showNotification(data, target){
    clearContainer(target);
    target.append('<p>'+data+'</p>');
}

function clearContainer(container){
    container.html('');
}
});

server.js

const _ = require('lodash');
const {ObjectID} = require('mongodb');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');

var {mongoose} = require('./db/mongoose');
var {Player} = require('./models/player');

var app = express();
const port = process.env.PORT || 3000;

app.use(express.static(__dirname+'./../public'));
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.sendFile('index.html');
});

app.post('/player', (req, res) => {
  var player = new Player({
    playername: req.body.playername,
    age: req.body.age,
    city: req.body.city,
    country: req.body.country,
    gender: req.body.gender,
    handedness: req.body.handedness,
    broom: req.body.broom,
    position: req.body.position,
    team: req.body.team,
    favoritecolor: req.body.favoritecolor,
    headshot: req.body.headshot
  });
  player.save().then((doc) => {
    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  });
});

app.get('/players', (req, res) => {
  Player.find().then((players) => {
    res.send(players);
  }, (e) => {
    res.status(400).send(e);
  });
});

app.get('/players/:id', (req, res) => {
  var id = req.params.id;
  if (!ObjectID.isValid(id)) {
    return res.status(404).send();
  }
  Player.findById(id).then((player) => {
    if (player) {
      res.send(player);
    } else {
      return res.status(404).send();
    }
  }).catch((e) => {
    res.status(400).send();
  });
});

app.delete('/players/:id/delete', (req, res) => {
  var id = req.params.id;
  if (!ObjectID.isValid(id)) {
    return res.status(404).send();
  }
  Player.findByIdAndRemove(id).then((player) => {
    if (player) {
      res.send(player);
    } else {
      return res.status(404).send();
    }
  }).catch((e) => {
    res.status(400).send();
  });
});

app.patch('/players/:id/edit', (req, res) => {
  var id = req.params.id;
  var body = _.pick(req.body, ['playername', 'age', 'city', 'country', 'gender', 'handedness', 'broom', 'position', 'team', 'favoritecolor', 'headshot']);
  if (!ObjectID.isValid(id)) {
    return res.status(404).send();
  }
  Player.findByIdAndUpdate(id, {$set: body}, {new: true}).then((player) => {
    if (!player) {
      return res.status(404).send();
    } else {
      res.send(player);
    }
  }).catch((e) => {
    res.status(400).send();
  })
});

app.listen(port, () => {
  console.log(`Started on port ${port}`);
});

module.exports = {app};

2 个答案:

答案 0 :(得分:1)

  

当我点击删除按钮时,我得到404状态代码,响应为&#34;无法获取/播放/ 123 /删除&#34;。如何调整显示代码以使用DELETE而不是GET? (我相信如果我能弄清楚如何在display.js代码中传递请求方法,我可以使用正确的http请求方法将我的所有路由重构为/ players /:id)。

这是因为您的应用已app.delete('/players/:id/delete')而非app.get('/players/:id/delete')。但是,您的服务器端代码不应该发生很大变化,只需进行一次调整:

  • 如果你有一个app.delete(),那么真的不需要在资源的末尾加上动词delete

此外,您需要使用HTTP方法DELETE发出请求,而不是在GET中生成display.js。只需使用DELETE $.ajax()请求,type设置为'DELETE'

  

当我点击编辑按钮时,我的GET / player /:id路由会获取正确的信息(状态代码200和预览显示JSON对象),但不会填充表单中的字段。

这是因为$.each()的实现假定data始终是一个数组而不是对象,但是,generateForm()传递的是Player对象。更改$.each()以进行数组检查以进行数组处理和对象处理。见以下变化。

  

当我尝试提交新记录时,我收到400状态代码,其中包含验证错误,指出需要使用Path age。对于每个字段名称,它实际上是相同的错误,因此我假设我没有正确地将字段中的值传递给JSON对象。

如果您将上述更改改为generateForm(),则应解决此问题。

只需使用以下代码段并替换应用中的这些部分即可。

server.js

app.delete('/players/:id', (req, res) => {
  var id = req.params.id;
  if (!ObjectID.isValid(id)) {
    return res.status(404).send();
  }
  return Player.findByIdAndRemove(id).then((player) => {
    if (player) {
      res.status(200).json(player);
    } else {
      return res.status(404).send();
    }
  }).catch((e) => {
    res.status(400).send();
  });
});

app.patch('/players/:id', (req, res) => {
  var id = req.params.id;
  var body = _.pick(req.body, ['playername', 'age', 'city', 'country', 'gender', 'handedness', 'broom', 'position', 'team', 'favoritecolor', 'headshot']);
  if (!ObjectID.isValid(id)) {
    return res.status(404).send();
  }
  Player.findByIdAndUpdate(id, {$set: body}, {new: true}).then((player) => {
    if (!player) {
      return res.status(404).send();
    } else {
      res.status(200).json(player);
    }
  }).catch((e) => {
    res.status(400).send();
  })
});

app.post('/players', (req, res) => {
  var player = new Player({
    playername: req.body.playername,
    age: req.body.age,
    city: req.body.city,
    country: req.body.country,
    gender: req.body.gender,
    handedness: req.body.handedness,
    broom: req.body.broom,
    position: req.body.position,
    team: req.body.team,
    favoritecolor: req.body.favoritecolor,
    headshot: req.body.headshot
  });

  return player.save().then((doc) => {
    return res.status(200).json(doc);
  }, (e) => {a
    return res.status(400).send(e);
  });
});

display.js

// Handle form submit event for both update & create
// if the ID_FIELD is present the server would update the database otherwise the server would create a record in the database
$('#container').on('submit', '#my-form', function(event) {
    var id = $('#id').val();
    let formData = {};

    $.each($('#myForm').serializeArray(), function(_, kv) {
          if (formData.hasOwnProperty(kv.name)) {
            formData[kv.name] = $.makeArray(formData[kv.name]);
            formData[kv.name].push(kv.value);
          }
          else {
            formData[kv.name] = kv.value;
          }
        });

    console.log(id);
    if (id != "") {
        event.preventDefault();
        $.ajax({
            url: baseURL + '/players/' + id,
            type: 'PATCH',
            success: function(edited) {
                // Handle returned edited player
            }
        })
    } else {
        event.preventDefault();
        $.ajax({
            url: baseURL + '/players',
            type: 'POST',
            success: function(created) {
              // Handle created player
            }
        })
    }
});

// Handle table click event for delete
$('#container').on('click', '.delete', function(event) {
    var id = $(this).val();
    // change the url parameters based on your API here
    // remember to create delete functionality on the server side (Model and Controller)
    // Using an JQuery AJAX GET request to get data form the server
    $.ajax({
        url: baseURL + '/players/' + id,
        type: 'DELETE',
        success: function(data) {
          //Generate table again after delete
        //change the url based on your API parameters here
        // Using an JQuery AJAX GET request to get data from the server
        $.getJSON(baseURL+'/players', function(data) {
            generateTable(data, $('#container'));
        });
        }
    });
});

// function to generate form
function generateForm(data, target){
    clearContainer(target);
    //Change form according to your fields
    $(target).append('<form id="my-form"></form>');
    var innerForm = '<fieldset><legend>Player Form</legend><p><label>Player Name: </label>'+'<input type="hidden" name="id" id="id"/>'+'<input type="text" name="playername" id="playername" /></p>' + '<p><label>Age: </label><input type="text" name="age" id="age" /></p>'+ '<p><label>Hometown: </label><input type="text" name="city" id="city" />'+ ' ' + '<input type="text" name="country" id="country" /></p>' + '<p><label>Gender: </label><input type="text" name="gender" id="gender" /></p>'+ '<p><label>Handedness: </label><input type="text" name="handedness" id="handedness" /></p>'+ '<p><label>Broom: </label><input type="text" name="broom" id="broom" /></p>'+ '<p><label>Position: </label><input type="text" name="position" id="position" /></p>'+ '<p><label>Team: </label><input type="text" name="team" id="team" /></p>'+ '<p><label>Favorite Color: </label><input type="text" name="favoritecolor" id="favoritecolor" /></p>'+ '<p><label>Headshot: </label><input type="text" name="headshot" id="Headshot" /></p>'+ '<input type="submit"/>';
    $('#my-form').append(innerForm);

    //Change values according to your data
    if(data instanceof Array){
        $.each(data, function(index, val) {
            $('#id').val(val._id);
            $('#playername').val(val.playername);
            $('#age').val(val.age);
            $('#city').val(val.city);
            $('#country').val(val.country);
            $('#gender').val(val.gender);
            $('#handedness').val(val.handedness);
            $('#broom').val(val.broom);
            $('#position').val(val.position);
            $('#team').val(val.team);
            $('#favoritecolor').val(val.favoritecolor);
            $('#Headshot').val(val.headshot);
        });
    }
    else if (typeof data === 'object') {
        $.each(data, function(key, value) => {
            $('#' + key).val(value);
        });
    }
}

答案 1 :(得分:0)

尝试使用res.json(player);代替res.send(player);,以便以JSON格式发送数据。

此外,代替$.post(url, form.serialize(), function(data) {尝试this answer中的代码,以便以JSON格式发送数据。