简体   繁体   中英

How to access formdata response in angular

Component.ts

 upload() {
      var formData: any = new FormData();
      formData.append('file', this.name);
      this.http.post('/temp/upload', formData,{responseType: 'text' })
        .subscribe((response) => {
             console.log('response received is ', response);
             if(response.code==400){
    alert("Upload success")
    }
    else{
    alert("Upload failed")
    }

      });}

server.js

 //upload
    router.post('/upload){
    if(!error){
       res.send({
             code: 400,
             success: "Upload success"
              });
    else{
    res.send({
    code:200
    }}
    }

The above upload function returns code:400 on success, The problem is I'm able to access "Property 'code' does not exist on type 'string'"

Thanks in advance

I think you get a string. Then you should parse the JSON string via JSON.parse(response).

An other try: responseType: 'text' -> responseType: 'json'

this.http
  .post('/temp/upload', formData, {responseType: 'json'})
  .subscribe((response) => {
      const res = (typeof response === 'string') ? JSON.parse(response): response;
      console.log('response received is ', res);
    },
    (error) => console.error(error)
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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