![](/img/trans.png)
[英]How to make a POST request to a nodejs RESTful API in reactjs
[英]Nodejs restful API unable to POST
我已經使用可在redis上運行的nodejs創建了一個REST API,我能夠使用get方法調用api,並且可以正常工作,但是當我將其更改為post並嘗試使用post調用時。 我收到錯誤消息Cannot POST
。 我在下面附加我的代碼,您能告訴我我在做什么錯嗎?
app.post('/foobar/:ticketid/:date/:from_time/:to_time/:seats', function(req, res) {
var id = req.params.ticketid;
var date = req.params.date;
var seats = req.params.seats;
var from_time = req.params.from_time;
var to_time = req.params.to_time;
var key = id + date;
var result = {};
client.exists(key, function(err, reply) {
if (reply === 1) {
//console.log("Key Found data from key: ");
client.get(key, function(err, reply) {
var output = JSON.parse(reply);
var data = [];
output.forEach(function(entry) {
var temp = {};
temp['from_time'] = entry["from_time"];
temp['to_time'] = entry["to_time"];
if ((entry["from_time"] == from_time) && (entry["to_time"] == to_time)) {
temp['vacancies'] = entry["vacancies"] - seats;
} else {
temp['vacancies'] = entry['vacancies'];
}
data = data.concat(temp);
});
client.set(key, JSON.stringify(data));
result['response'] = 1;
result['message'] = 'vacancies successfully updated!';
res.json(result);
});
} else {
result['response'] = 0;
result['message'] = 'Invalid timeslot!';
res.json(result);
}
});
});
我使用郵遞員和Rest easy插件打電話。 在url中,我放置http://xxx.xxx.xxx.xxx:8081/foobar/
;在正文中,我放置鍵值對
郵遞員的代碼:
POST /foobar/ HTTP/1.1
Host: xxx.xxx.xxx.xxx:8081
Authorization: Basic NDM5OlA5MS1RVDhQLUs4RzktTDU2
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Cache-Control: no-cache
Postman-Token: ab3cb383-62d4-475f-0e59-881a167156eb
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="ticketid"
251
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="date"
2016-05-14
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="from_time"
18:00
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="to_time"
21:00
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="seats"
5
------WebKitFormBoundary7MA4YWxkTrZu0gW--
如果要在正文中發布值,則無需在URL中列出它們。 只要確保您的標頭設置為"Content-Type": "application/json"
app.post('/foobar', function(req, res) {
var id = req.body.ticketid;
var date = req.body.date;
var seats = req.body.seats;
var from_time = req.body.from_time;
var to_time = req.body.to_time;
....
}
這不是傳遞參數並獲取它的正確方法
試試這個
app.post('/foobar/ticket/:ticketid/date/:date/from_time/:from_time/to_time/:to_time/seats/:seats
並以這種方式從客戶端發布
/foobar/ticket/123/date/your date/from_time/your date/to_time/your time/seats/123234
像這樣得到它
使用req.params
檢查所有參數
var id = req.params.ticketid;
var date = req.params.date;
var seats = req.params.seats;
var from_time = req.params.from_time;
var to_time = req.params.to_time;
var key = id + date;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.