【问题标题】:Nodejs not receiving post data from AngularNodejs没有从Angular接收帖子数据
【发布时间】:2021-07-24 06:00:00
【问题描述】:

我有一个 MEAN Stack Web 应用程序,我正在尝试注册用户。如果我使用 Insomnia/Postman 发出 POST 请求,我成功注册了用户。但是,当我从 Angular 10 发送请求时,我得到一个空的请求正文 {}。我还在 Angular 服务中打印了数据,以查看我发送的内容以及数据是否存在。我不明白为什么它适用于 Insomnia/Postman 而不是 Angular。

这是 Angular 代码:

signup.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from 'src/app/services/authentication.service';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss']
})
export class SignupComponent implements OnInit {

  constructor(private router: Router, private authenticationService: AuthenticationService) { }

  ngOnInit() {
  }

  submitSignUpForm(data) {
    var formData = new FormData()
    formData.append('email', data.email)
    formData.append('password', data.password)
    formData.append('fullname', data.firstname + ' ' + data.lastname)      
    this.authenticationService.registerUser(formData).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
  }
}

authentication.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  serverURL = ""

  constructor(private http: HttpClient) {
    this.serverURL = <SERVER_URL>
  }

  registerUser(data) {
    return this.http.post(`${this.serverURL}/auth/register`, data)
  }
}

server.js

....

app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: true
}))
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(express.urlencoded({extended: true}))
app.use(express.json())
app.use(express.static(path.join(__dirname, 'public')))

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

....

如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: node.js angular mean-stack angular10


    【解决方案1】:

    我从Angular 7 not sending HTTP Post request data的帖子中找到了解决方案

    我将此添加到 authentication.service.ts

    import { HttpHeaders } from '@angular/common/http';
    
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
        })
    };
    

    并添加 httpOptions 作为第三个参数来发布请求

    【讨论】:

      猜你喜欢
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      相关资源
      最近更新 更多