簡體   English   中英

帶有“表單數據”類型的請求正文參數的POST不起作用+角度2

[英]POST with request body params of type 'form-data' not working + angular 2

我在郵遞員中使用'form-data'類型在正文中發送文件和其他參數,並且工作正常。 我想在角度2中做同樣的事情。請在郵遞員中找到請求的快照: 在此處輸入圖片說明

另外,找到我無法使用的角度代碼。 這有什么問題:

let formData: FormData = new FormData();
        formData.append('file', file);
        formData.append('pid', 2);
        formData.append('cid', 4);
        let headers = new Headers();
        headers.append('Authorization', '5C7D01DD-95F5-44CA-B897-012B218D80012');
        let requestOptions = new RequestOptions({ headers: headers });
        console.log('API call: to upload lead file');
        return this.http.post("http://blahblha.com" + LeadApi, formData, requestOptions)
            .retryWhen((error) => error.delay(this.appConfig.serviceCallRetryDelay))
            .timeout(this.appConfig.serviceCallRetryTimeOut)
            .map((response: Response) => response.json());

I am getting Error 500- Internal Server Error

另外,附有來自網絡的請求有效負載:

------WebKitFormBoundaryzbq2nbK8gMNeqBck
Content-Disposition: form-data; name="file"; filename="Testleads.csv"
Content-Type: application/vnd.ms-excel


------WebKitFormBoundaryzbq2nbK8gMNeqBck
Content-Disposition: form-data; name="pid"

2
------WebKitFormBoundaryzbq2nbK8gMNeqBck
Content-Disposition: form-data; name="cid"

4
------WebKitFormBoundaryzbq2nbK8gMNeqBck--

我在angular2中做錯了什么?

首先創建一個Angular2服務,以便您可以訪問它,並在需要獲取或發布數據時僅調用方法。

服務:

@Injectable()
export class ApiService {
    private headers = new Headers({'Content-Type': 'application/form-data; charset=UTF-8'});

    constructor(private http: Http) {
    }

    public send(url, body: Object): Observable<any> {
        let bodyString = this.serializeObj(body);

        return this.http
            .post(url, bodyString, {headers: this.headers})
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        if (body) {
            return body.data || body;
        } else {
            return {};
        }
    }

    private handleError(error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }

    private serializeObj = function (obj, prefix = null) {
        let str = [], p;
        for (p in obj) {
            if (obj.hasOwnProperty(p)) {
                let k = prefix ? prefix + '[' + p + ']' : p, v = obj[p];
                str.push((v !== null && typeof v === 'object') ?
                    this.serializeObj(v, k) :
                    encodeURIComponent(k) + '=' + encodeURIComponent(v));
            }
        }
        return str.join('&');
    };
}

在您的組件中:

constructor(private apiService: ApiService) {
    let mySendingObject = {}; // This is the object you send in your POST
    this.sendData(mySendingObject); // And here we are actually calling our method that uses the post method within ApiService
}

sendData(myObj) {
   let url = 'http://blahblha.com' + LeadApi;
   return this.apiService.send(url, myObj);
}

在需要發送帖子的地方,只需在組件內部調用sendData()方法sendData()

通過這種方式,您可以實現以下幾點:

  • 您將api服務與應用程序的其余部分分離了
  • 您可以創建導入ApiService的更特定的服務。 例如:導入並使用ApiService UserService
  • 我們有以下方法:
    • 處理調用中的錯誤: handleError()
    • 提取數據: extractData()
    • 序列化對象: serializeObj()

結構應類似於:

  • ApiService :使用Http管理API調用(發布,獲取等)
    • 本地服務,例如: UserService :導入ApiService並具有諸如: updateUserdeleteUseraddUser等方法。
      • 組件,例如: UsersViewComponent :使用UserService並通過view與之交互。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM