2016-08-19 41 views
1

我是新來的節點/快遞JS,有一個簡單的應用程序,它在HTML這給了我一個404未找到錯誤提供了一個index.html發送數據使用jQuery到節點應用

$.ajax({ 
     type: 'POST', 
     url: url + "/json/addData'", 
     contentType: 'application/json', 
     data: {"app" : JSON.stringify("ID=10")}, 
     cache: false, 
     success: function (result) { console.log(result); } 
}); 

但能正常工作

http://localhost:8081/api/json/addData?id=10 

此功能在快遞應用實例中運行

app.get('/api/json/addData/', function (req, res) { 
    console.log(req.query.id); 
    res.send("Success"); 
}); 

改變功能時,app.post我仍然獲得了404 改變阿賈克斯拿到我再次得到一個404錯誤

這將是後一個JavaScript對象的正確方法(或它的值)到一個節點的應用程序,以及如何接收它?

對於noob問題感到抱歉。所有的搜索帶來到目前爲止,還沒有工作的結果對我來說

+0

表達的版本您使用的?我發現這與表達4有關:https://codeforgeek.com/2014/09/handle-get-post-request-express-4/。看來你需要一些額外的工作才能讓app.post()工作。不過,我沒有嘗試解決方案,但也許有幫助。 GL – Sergeon

回答

0

您需要發佈正確的API網址和發送正確的參數作爲與PARAM是ID和值爲10

$.ajax({ 
     type: 'POST', 
     url: "http://localhost:8080/api/json/addData'", 
     contentType: 'application/json', 
     data: {"id" : "10"}, 
     cache: false, 
     success: function (result) { console.log(result); } 
}); 

你需要數據的查詢一箇中間件來解析app.post中的參數。這是一個身體解析器

npm install --save body-parser 

使用

var bodyParser = require('body-parser') 
app.use(bodyParser.json());  // to support JSON-encoded bodies 
app.use(bodyParser.urlencoded({  // to support URL-encoded bodies 
    extended: true 
})); 

app.use(express.json());  // to support JSON-encoded bodies 
app.use(express.urlencoded()); // to support URL-encoded bodies 

app.post('/api/json/addData/', function (req, res) { 
    console.log(req.query.id); 
    res.send("Success"); 
}); 
+0

謝謝,但不能全部。快速應用程序功能仍然app.get,所以我仍然404。如何正確接收JSON數據? – user3732793

+0

感謝編輯,我試過了,但現在我得到了關於缺失的中間件json的抱怨......另一個問題。我會同意您的解決方案一旦修復並檢查..感謝 – user3732793

+0

現在安裝在節點端的一切。我從你的ajax例子中收到不好的請求。任何想法爲什麼? – user3732793

相關問題