0

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

我的代码

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;
4

1 回答 1

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);
      });
  }
于 2019-03-19T23:03:23.397 回答