无法将表单数据从前端(Angular4)发布到后端(NodeJS)

时间:2018-04-02 14:38:51

标签: node.js angular

****场景:****我的要求是将表单数据从前端(角度)发送到后端(nodeJS)。我使用了Angular模板表单并将表单数据POST到Node JS API进行进一步处理。但是我无法在后端看到数据。如果我从邮递员发送数据但不通过前端发送数据,则此API有效。下面的API代码中的req.body没有表单数据,而是返回一个null对象。请帮我解决这个问题。

API代码

let express = require('express');
let bodyParser = require('body-parser');
let email = require('./emailSender.js');
let port = process.env.PORT || 3100;
let app = express();

let urlencodedParser = bodyParser.urlencoded({extended:false});

// app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
 app.use((req,res,next) =>{
     res.setHeader("Access-Control-Allow-Origin","*" );
     res.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-with,Content-Type,Accept,Authorization");
     if(req.method==="OPTIONS"){
         res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
         return res.status(200).json({});
     }
      next();
 });

app.post('/email/feedback',urlencodedParser,(req,res) =>{  
    console.log('API is called');
    console.log(req.body);
    email(req.body.subject,req.body.comment);
    res.send(req.body);    
});

app.listen(port,()=>console.log(`Server is running on the port ${port}`));

前端代码(角形模板表格)

<div class="col-6"> 
<form #f="ngForm" (ngSubmit)="submit(f)">
    <div class="form-group">
      <label for="fullName">Name</label>
      <input  ngModel name="fullName" 
              #name="ngModel"
              type="text" 
              class="form-control"               
              >     
    </div> 

    <div class="form-group">
        <label for="email">Email Address</label>
        <input  ngModel name="email" 
                #name="ngModel"
                type="email" 
                class="form-control"                 
                >     
      </div> 

      <div class="form-group">
          <label for="subject">Subject</label>
          <input  ngModel name="subject" 
                  #name="ngModel"
                  type="text" 
                  class="form-control"                 
                  >     
        </div> 
        <div class="form-group">
            <label for="comment">Comment</label>
            <textarea rows="10" cols="30"
                    ngModel name="comment" 
                    #name="ngModel"
                    class="form-control">
            </textarea>                
        </div>

        <button class="btn btn-primary"> Submit</button>
    </form>
</div>

组件代码

import { Component, OnInit } from '@angular/core';
import { EmailService } from '../services/email.service';

@Component({
  selector: 'app-feedback',
  templateUrl: './feedback.component.html',
  styleUrls: ['./feedback.component.css']
})

export class FeedbackComponent implements OnInit {
  response;

  constructor(private email:EmailService) { }

  ngOnInit() {

  }

  submit(f){
  //  console.log(f.value);
   let feedback ={
     subject:f.value.subject,
     comment:f.value.comment
   }

     this.email.sendFeedback(feedback)
         .subscribe(response => {this.response=response;
                    console.log(this.response)});
  }

}

服务代码

import { Injectable } from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class EmailService {

  url="http://localhost:3100/email/feedback";
//JSON.stringify(feedback)
  constructor(private http:Http) { }

  sendFeedback(feedback){
    return this.http.post(this.url,JSON.stringify(feedback));

  }


}

1 个答案:

答案 0 :(得分:0)

尝试此操作,在从前端传递表单数据时添加以下Content-Type。

Content-Type: multipart/form-data;

当您从邮递员调用multipart / formdata时,默认情况下会添加内容类型。因此,您可以在req.body中获取数据,但是当涉及到前端时,您需要手动传递内容类型,如上所述。

我希望这会对你有所帮助。如果您仍有问题或需要任何澄清,请告诉我。