简体   繁体   English

Angular2 http put方法不发送formData

[英]Angular2 http put method not sending formData

I'm trying to send a PUT request from Angular2 (using typescript) to an API made with Laravel. 我正在尝试将Angular2的PUT请求(使用打字稿)发送到使用Laravel制作的API。 I'm doing it with the FormData class because this is how I can attach a file to the request. 我正在使用FormData类,因为这是我可以将文件附加到请求的方式。 The POST method is working great, but when I try to update my model with a PUT method the API receives an empty request. POST方法的效果很好,但是当我尝试使用PUT方法更新模型时,API会收到一个空请求。

I've made some debugging and the FormData contains the data as expected, so I'm almost sure that my data is getting lost at the PUT request. 我已经进行了一些调试,并且FormData包含了预期的数据,因此我几乎可以确定我的数据在PUT请求中丢失了。

Service: 服务:

import {Http, Headers, Response, RequestOptions} from "@angular/http";

@Injectable()
export class SensorService {

public data: Data[] = [];
public sensors: Sensor[] = [];

constructor(private http: Http,
          private authService: AuthService) {

}

updateSensor(id: number, nombreNevera: string, ciudad: string, empresa_id: number,
           tipoSensor: string, telefonoMarcado: number,
           telefonoMarcadoB: number = null, telefonoMarcadoC: number = null,
           telefonoMarcadoD: number = null, fechaCalibracion: number = null,
           temMax: number = null, temMin: number = null, humeMax: number = null,
           humeMin: number = null, correos: any = null, fileToUpload: any = null) {

let formData: FormData = new FormData();

formData.append('nombreNevera', nombreNevera);
formData.append('cuidad', ciudad);
formData.append('empresa_id', empresa_id);
formData.append('tipoSensor', tipoSensor);
formData.append('telefonoMarcado', telefonoMarcado);
formData.append('telefonoMarcadoB', telefonoMarcadoB);
formData.append('telefonoMarcadoC', telefonoMarcadoC);
formData.append('telefonoMarcadoD', telefonoMarcadoD);
formData.append('fechaCalibracion', fechaCalibracion);
formData.append('humeMax', humeMax);
formData.append('humeMax', humeMin);
formData.append('temMin', temMin);
formData.append('temMax', temMax);
formData.append('correos', JSON.stringify(correos));

if (fileToUpload != null) {
  formData.append('certificado', fileToUpload, fileToUpload.name);
}

const headers = new Headers({
  'X-Requested-With': 'XMLHttpRequest'
});

return this.http.put(APPCONSTANTS.API_ENDPOINT + 'user/sensor/edit/' + id + '?token=' + this.authService.getToken(),
  formData,
  {headers: headers})
  .map((response: Response) => {
    return {
      msg: response.json().msg
    };
  });

}

}

Laravel returns an "Unprocessable Entity" because of the required fields in the controller. 由于控制器中的必填字段,Laravel返回“无法处理的实体”。

you can make put request like this 您可以这样发出看跌期权

let headers = new Headers({ 'Content-Type': 'application/json', 
                                         'Accept': 'application/json;' });

         let options = new RequestOptions({ headers: this.headers });

     let body = JSON.stringify(formData);

    return this.http.put(APPCONSTANTS.API_ENDPOINT + 'user/sensor/edit/' + id + '?token=' + this.authService.getToken(),
      body ,options)
      .map((response: Response) => {
        return {
          msg: response.json().msg
        };
      });

Z. Bagley made me think that this could be a Laravel related problem and in fact it is. Z. Bagley让我认为这可能是与Laravel相关的问题,实际上是这样。 There's this bug causing errors when using multipart/form-data and a PUT request. 使用multipart / form-dataPUT请求时, 此错误会导致错误。

I solved the problem sending a POST request and adding _method to the form, ending with a request like this: 我解决了发送POST请求并在表单中添加_method的问题,以这样的请求结尾:

formData.append('_method', 'PUT');

const headers = new Headers({
  'X-Requested-With': 'XMLHttpRequest'
});
return this.http.post(APPCONSTANTS.API_ENDPOINT + 'user/sensor/edit/' + id + '?token=' + this.authService.getToken(),
  formData,
  {headers: headers})
  .map((response: Response) => {
    return {
      msg: 'sensor_updated'
    };
  });

You can let the Laravel API to listen for a PUT request: 您可以让Laravel API监听PUT请求:

Route::put('/sensor/edit/{id}', [
    'uses' => 'NeveraController@update'
])->middleware('jwt.auth');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM