2017-05-29 20 views
0

我正在使用基本提取從查詢數據庫中的數據的快速服務器獲取數據。所以我想做一個登錄系統,我想通過提取請求從輸入字段發送用戶/密碼。所以我可以執行邏輯檢查以查看密碼是否與服務器中的數據相匹配。並對結果做出迴應。 是否可以執行可以傳遞參數的提取?提取:您可以將參數傳遞到服務器

更新一下代碼:

let fetchData = { 
    method: "post", 
    headers: { 
    'Accept': 'application/json', 
    'Content-Type': 'application/json' 
    }, 

    body: JSON.stringify({ 
    username: this.state.user, 
    password: this.state.password 
    }) 
} 

var fromServer = fetch('http://localhost:3000/', fetchData) 
.then(function(response){ 
    if(!response.ok){ 
    throw Error (response.statusText); 
    } 
    return response.json(); 
}) 
.then(function(response) { 
    console.log(response); 
}) 
.catch(error => console.log("there was an error --> " + error)); 

快遞功能

app.post('/', function(req, res){ 
    var uname = req.body.username; 
    var pw = req.body.password; 
    console.log(uname); 
    console.log(pw); 
}); 

回答

2

當然可以!

下面是一個使用POST請求獲取的例子:

fetch("http://example.com/api/endpoint/", { 
    method: "post", 
    headers: { 
    'Accept': 'application/json', 
    'Content-Type': 'application/json' 
    }, 

    //make sure to serialize your JSON body 
    body: JSON.stringify({ 
    name: myName, 
    password: myPassword 
    }) 
}) 
.then((response) => { 
    //do something awesome that makes the world a better place 
}); 

我以前回答過這個問題,請在此瞭解更多詳情:

POST Request with Fetch API?

要處理請求Express,如您的評論中所述,假設您的快速服務器設置爲解析主體請求,您可以這樣做:

app.post('/your/route', function(req, res) { 
    var name= req.body.name; 
    var password = req.body.password; 

    // ...do your bidding with this data 
}); 
+0

哦,好吧,在服務器端,我只是做一個app.get?或app.post函數? – Eric

+0

根據我的示例,假設您正在使用ExpressJS,則app.post()是您處理該請求所需的。 – hellojebus

+0

啊好吧謝謝,生病了試試看。 – Eric