node.js multer-req.file未定义

时间:2019-08-18 03:58:41

标签: node.js angular file-upload multer

具有multer中间件的节点/快速后端服务器无法使用从带有http拦截器的angular7 / http客户端上传的多部分/表单数据图像文件。


将api发送到服务器上,其中包含以下代码,报告 req.file undefined     
    服务器-node.js / express / multer     
    
使用客户端上传图像文件-Angular 7->组件-> uploadsrvice(@ angular / common / http)-> http拦截器  
    ``

    node.js api server code

    const express = require('express');
    const cors = require('cors');
    let appiu = express();
    appiu.use(cors({origin: tru }));
    appiu.use('/', function (req, res, next) { 
        console.log('req.headers --->', req.headers);
      next();
    })
    const multer = require('multer');
    var mstorage1 = multer.diskStorage({
        destination: function (req, file, cb) {
            console.log("reached multer");
          cb(null, './keys/images/');
        },
        filename: function (req, file, cb) {
            console.log("reached multer",file.originalname);
          cb(null, Date.now() + file.originalname);
        }
      });

    var upload1 = multer({    storage: mstorage1}).single('image');

     appiu.post('/photos/image-upload',
       function (req, res) {

        upload1(req,res,function(err){
            console.log("req.file", req.file);
            console.log("req.files", req.files);
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
             res.json({error_code:0,err_desc:null});
        });

      });

````

console.log('req.headers --->',req.headers);报告

 ````

    { 'accept-language': 'en-US,en;q=0.9',
      'accept-encoding': 'gzip, deflate, br',
      referer: 'http://localhost:4200/upload',
      'sec-fetch-site': 'same-site',
      origin: 'http://localhost:4200',
      'content-type':
      'multipart/form-data; boundary=----WebKitFormBoundaryc8BWedVBAK9DP0Ng', 
      'sec-fetch-mode': 'cors',
      'user-agent':
       'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
      accept: 'application/json, text/plain, */*',
      'content-length': '166498',
      connection: 'close',
      host: 'localhost:5000' }

````

console.log(“ req.file”,req.file);  console.log(“ req.files”,req.files);

reports 


信息:需求文件未定义
info:需求文件未定义     


感谢您提供任何帮助解决为什么 req.file 在服务器上不可用的帮助。
 这是客户端代码

````

    onSubmit() {
        const formData = new FormData();
        formData.append('name', this.profileForm.get('name').value);
        formData.append('profile', this.profileForm.get('profile').value);

         this.fileUploadService.upload(formData);

      }
    // angular http call service 
    return this.http.post<any>(`${this.apiUrl}`, formData, {
                reportProgress: true,
                observe: 'events'
            }).
                subscribe((event: HttpEvent<any>) => {
                    switch (event.type) {
                        case HttpEventType.Sent:
                            console.log('Request sent!');
                            break;
                        case HttpEventType.ResponseHeader:
                            console.log('Response header received!');
                            break;

                        case HttpEventType.Response:
                            console.log('Http post  Done!', event.body);
                        case HttpEventType.UploadProgress:
                            return this.fileUploadProgress(event);
                        case HttpEventType.Response:
                            return this.apiResponse(event);

                        default:
                            return `File "${formData.get('profile').name}" surprising upload event: ${event.type}.`;

                    }
                });

//http interceptor


    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

            console.log("http request intercepted by HttpConfigInterceptor"+JSON.stringify(request.headers));
            // lets add the base url first.





            if (request.body instanceof FormData) {
                // we are sending a file here
                console.log("sending a multipart/form-data");

              }
            if (request.url.indexOf('photos/image-upload') == 0) {

                console.log('photos/image-upload true')
                request = request.clone({ url: `${environment.rootUrlIU}/${request.url}` });



            }
            else {
                request = request.clone({ url: `${environment.rootUrl}/${request.url}` });
            }

            return next.handle(request)
                .pipe(
                    map((event: HttpEvent<any>) => {
                        if (event instanceof HttpResponse) {
                            console.log('HttpConfigInterceptor response event--->>>', event);

                        }
                        return event;
                    }),
                    catchError((error: HttpErrorResponse) => {
                        let data = {};
                        data = {
                            reason: error && error.error && error.error.reason ? error.error.reason : '',
                            status: error.status
                        };




                        return throwError(error);
                    }));
        }
````

    enter code here

Any help highly appreciated.. thank you.

0 个答案:

没有答案