Angular向节点API发送请求

时间:2019-03-19 19:46:37

标签: json angular request body-parser nodejs-server

在我的有角度的应用程序中,我向带有JSON数据对象的Node API发送了一个post请求,但该请求无法正常工作。在请求有效负载中,未显示JSON数据对象。 当我使用JSON.stringify(auth)发送JSON字符串时,它会显示在请求有效负载中,但无法由节点后端的json body-parser进行解析。请求正文为空。给我解决这个问题的方法。

我的代码

import { Injectable } from "@angular/core";
import { AuthData } from "../modules/AuthData";
import {
  HttpClient,
  HttpParams,
  HTTP_INTERCEPTORS,
  HttpInterceptor,
  HttpHeaders
} from "@angular/common/http";
@Injectable({
  providedIn: "root"
})
export class AuthService {
  private url = "http://localhost:3000";
  private httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      Authorization: "my-auth-token",
      "Request-Method": "post"
    })
  };
  constructor(private http: HttpClient) {}

  login(email: string, password: string) {
    const authData = { email: email, password: password };
    console.log(authData);
    this.http
      .post(this.url + "/api/user/login", authData)
      .subscribe(response => {
        console.log(response);
      });
  }
}

我的后端代码

    const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require("mongoose");
const cors = require('cors');
const userRoute = require("./routes/user");

const app = express();

mongoose
  .connect('mongodb://localhost:27017/tryondb', {
    useNewUrlParser: true
  })
  .then(() => {
    console.log("connected to the database");
  })
  .catch(() => {
    console.log("connection failed");
  })

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
//var jsonParser = bodyParser.json();
//var urlencodedParser = bodyParser.urlencoded({ extended: false });

//app.use(cors);
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Header",
    "Origin, X-Requested-with, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, DELETE, OPTIONS"
  );
  console.log("rrr");
  next();
})





app.post("/api/user/login",(req,res,next)=>{
  console.log(req);
});

app.use("/api/user", userRoute);
console.log("aaa");
module.exports = app;

1 个答案:

答案 0 :(得分:0)

您正在创建httpoptions,但未正确传递它们:请尝试

 login(email: string, password: string) {
    const authData = { email: email, password: password };
    console.log(authData);
    this.http
      .post(this.url + "/api/user/login", authData, httpOptions)
      .subscribe(response => {
        console.log(response);
      });
  }