Express框架Fetch通訊

最近本身弄個博客站點,前臺用的React,服務器用的是node實現的,node是第一次接觸,因此還在摸索,這篇mark下通訊時遇到的坑。node

fetch配置:express

 1 window.fetchUtility = function (options, errorFun) {
 2     var request = {
 3         method: 'POST',
 4         headers: {
 5             'Content-Type': 'application/x-www-form-urlencoded'
 6         },
 7         // headers: {
 8         //     'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
 9         //     'Accept': 'application/json'
10         // },
11         cache: 'no-store',
12         body:`userName=${options.data.userName}&password=${options.data.password}`
13     };
14     if (request.method.toLowerCase() === "get") {
15         request.body = null;
16     }
17     return fetch(options.url, request)
18         .then(function (response) {
19             if (response.ok) {
20                 if (request.download) {
21                     return response;
22                 }
23                 else {
24                     return response.text().then(function (dataString) {
25                         return {
26                             responseStatus: response.status,
27                             responseString: dataString,
28                             isParseJson: request.isParseJson,
29                             isPassStatus: request.isPassStatus
30                         };
31                     });
32                 }
33             } else {
34                 if (response.status == 403) {
35                     window.location.href = "/error/" + response.status;
36                 } else if (response.status == 409) {
37                     // for simulation
38                     $$.alert(true, { type: "w", content: "Sorry, currently you are in simulation mode and limited to read only access." });
39                     throw new Error("simulation");
40                 }
41                 else {
42                     if (errorFun) {
43                         errorFun(response);
44                     }
45                     else {
46                         throw new Error(response.statusText);
47                     }
48                 }
49             }
50         }).then(function (fetchResult) {
51 
52             if (request.download) { return fetchResult };
53 
54             var queryResult = null;
55 
56             try {
57                 if (!fetchResult.responseString) {
58                     return null;
59                 }
60                 if (fetchResult.isParseJson && fetchResult.responseString) {
61                     if ($.isEmptyObject(fetchResult.responseString)) {
62                         queryResult = "";
63                     } else {
64                         queryResult = JSON.parse(fetchResult.responseString);
65                         if (fetchResult.isPassStatus) {
66                             queryResult[FetchResponsePropName.status] = fetchResult.responseStatus;
67                         }
68                     }
69                 } else {
70                     queryResult = fetchResult.responseString;
71                 }
72             }
73             catch (ex) {
74                 $$.error("An error happened while fetching information. Error:", ex);
75             }
76             return queryResult;
77         });
78 };

GET通訊使用:json

 1  retrieve(){
 2         let option = {
 3             url: `./api/about/getAbout?test=${'dqhan'}`,
 4             method:'Get'
 5         }
 6         fetchUtility(option).then(res=>{
 7             var a = res;
 8         }).catch(e=>{
 9             console.log(e);
10         })
11     }

express接受參數形式:api

POST通訊:服務器

postRequest() {
        let data = {
            params: { test: 'test' }
        };
        let option = {
            url: `./api/about/postRequest`,
            method: 'Post',
            data: data
        }
        fetchUtility(option).then(res => {
            var a = res;
        }).catch(e => {
            console.log(e);
        })
    }

由於調試過程當中express中接受參數時一直接收不到,因此mark下(node小白,正在努力ヾ(◍°∇°◍)ノ゙)app

問題緣由:post

對node的不熟悉,以及對fetch的不精通。fetch

先後臺通訊數據傳遞最基本的結構:ui

  1. header定義發送、接受的媒體類型
  2. 請求方式post、get等等
  3. body參數結構

以上三點是最基本的參數,然而我一直在糾結是否是還有什麼配置錯誤,因而一直在這裏打轉轉。
問題根本緣由是須要在node裏面使用body-parser來接受參數,這樣express才能解析通訊發過來的參數。
解決方法:url

var bodyParser  = require('body-parser');
const app = new express();
app.use(bodyParser.urlencoded({extended: true})) 

總結:

我應該好好看看node的文檔。sorry~

相關文章
相關標籤/搜索