jQuery Ajax Post - 404错误 - 本地服务器

时间:2017-02-14 02:02:21

标签: javascript jquery ajax post

我正在尝试使用本地服务器创建API进行测试。 ROUTES正在运行,我可以使用浏览器中的URL将数据添加到OBJ。问题是当我尝试通过HTML“发布”数据时。我收到了404错误。我使用node.js和Express开发。我做错了什么?

服务器端的JS

app.get('/add/:word/:score?', addWord);

//Function to request and send back the data
function addWord(request, response) {

var data = request.params;
var word = data.word;
var score = Number(data.score);
var reply;

if (!score) {
    var reply = {
        msg: 'Score is required'
    }
    response.send(reply);
} else {
    words[word] = score;
    // Transforms javascript object into raw data correctly idented with null, 2
    var data = JSON.stringify(words, null, 2);
    fs.writeFile('words.json', data, finished);

    function finished(err) {
        console.log('Writting');
        var reply = {
            word: word,
            score: score,
            status: 'Success'
        }
        response.send(reply);
    }
  }
}

POST方法JS

$('#submit').on('click', function submitWord() {
  var word = $('#fieldWord').val();
  var score = $('#fieldScore').val();

  $.ajax({
    type: 'POST',
    url: '/add/' + word + "/" + score,
    success: function (newOrder) {
      $list.append('<li>name: ' + newOrder.word + newOrder.score + '</li>');
    },
    error: function (err) {
      console.log('Error saving order', err);
    }
  });
});

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Tutorial API with node.js</title>
    <script type="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  </head>
  <body>

    <p>
      Word: <input type="text" id="fieldWord"><br/>
      Score:<input type="text" id="fieldScore"><br/>
      <button type="button" id ="submit">Submit</button>
      <ul id="list">
      </ul>
    </p>

  </body>
  <script type="text/javascript" src="sketch.js"></script>
</html>

提前谢谢。

0 个答案:

没有答案