【问题标题】:Browser Fetch() API Is Not Posting Body To Backend Node Server浏览器 Fetch() API 未将正文发布到后端节点服务器
【发布时间】:2018-11-29 13:30:29
【问题描述】:

客户端浏览器:

API

class API {

    constructor() {

        this.api = "http://localhost:3000";
    }

    async authenticate(product_id) {

        const url = this.api + '/api/auth';
        const body = {
            "product_id": product_id,
        }

        console.log(body);

        const request = {
            method: 'POST',
            body: body,
        }
        return await fetch(url, request);
    }
}

module.exports = API;

索引

const account = await this.API.authenticate("56729b6b77c82288f746c0cf");

console.log(account)

在我的控制台中我得到了

响应{类型:“cors”,网址:“http://localhost:3000/api/auth”, 重定向:false,状态:401,ok:false,...} body : (...) bodyUsed : 错误标头:标头{} ok:错误重定向:错误状态:401 statusText:“未经授权”类型:“cors”网址: "http://localhost:3000/api/auth"

Fetch 加载失败:POST "http://localhost:3000/api/auth"。

服务器端:

app.ts

import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import passport from 'passport';
import cors from "cors";

import Routes from './routes';
import Config from './config/config';

class App {

    public app: express.Application;
    public config: any;

    constructor() {

        this.app = express();

        this.environment();
        this.database();
        this.middleware();
        this.routes();

    }

    private environment(): void {

        this.config = new Config();

    }

    private database(): void {

        const uri: string = this.config.db.uri;
        const options: any = this.config.db.options;

        mongoose.connect(uri, options).then(

            () => {
                console.log("MongoDB Successfully Connected On: " + this.config.db.uri)
            },
            (err: any) => {
                console.error("MongoDB Error:", err);
                console.log('%s MongoDB connection error. Please make sure MongoDB is running.');
                process.exit();
            }

        );

    }

    private middleware(): void {

        this.app.use(cors());
        this.app.use(logger('dev'));
        this.app.use(express.json());
        this.app.use(express.urlencoded());
        this.app.use(passport.initialize());

    }

    private routes(): void {

        const routes = new Routes(this.app);

    }

}

export default App;

api/auth 路由

public store(req, res) {

      console.log(req.body)
}

req.body 为空。

【问题讨论】:

  • @Randy 否,因为该请求在邮递员中工作正常
  • @Randy 我更新了我的问题,向您展示了我的服务器端应用程序的代码。你可以看到我已经设置了 cors 和 bodyParser。
  • 我什至已经更新为使用 express.json 和 urlencoder 而不是 bodyparser,但这仍然不能解决问题。

标签: node.js express fetch


【解决方案1】:

您应该尝试在请求模式中添加:cors 在您的请求中。正文应该是一个字符串,您可能希望将内容类型的标头设置为 application/json:

let headers = new Headers();
headers.set('Content-type', 'application/json');

const request = {
    method: 'POST',
    body: JSON.stringify(body),
    mode: 'cors',
    credentials: 'include',
    headers: headers
}

查看浏览器网络选项卡中发生的情况也会很有帮助。

【讨论】:

  • 我的请求中不需要身份验证令牌/标题。是否仍需要模式和凭据?
  • 我已更新我的问题以包含浏览器的屏幕截图
  • 如果您在请求中传递 Cookie 或 Authorization 标头,则需要凭据,所以我想这不是必需的。抱歉,我错过了 fetch 调用中的其他一些问题。我更新了响应。
  • 对不起,我不明白你的意思。在我的身体 {} 中,您会看到我传入了一个 product_id 输入。我的请求没有使用任何授权头,它不需要它来调用 api。
  • @Kay 你也可以张贴带有请求和响应的 HTTP 标头的浏览器网络选项卡的屏幕截图。像这样的东西:stackoverflow.com/a/4423097/121199
猜你喜欢
  • 2020-03-29
  • 2011-09-04
  • 1970-01-01
  • 2013-06-25
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
相关资源
最近更新 更多