POST 请求显示未定义

POST request show undefined

我正在尝试将电子邮件地址作为 json 对象发送到 node express rest api 并将其打印在 html 文件中。该值由 index.js 提供。我希望电子邮件地址将打印在文件上,但我得到的所有信息都是未定义的,因此 console.log。我想知道我做错了哪一部分?这些文件如下所示。

客户postRequest.js

export function send(data={}) {
  return sendRequest('/send', data);
}

async function sendRequest(path, data={}) {
  const PATH = `${ROOT_URL}${path}`;
  const options = {'from' : data.from}
  const Settings = {
    method : 'POST',
    headers : {
      'Content-Type': 'application/json'
    },
    options
  };

  const response = await fetch(PATH, Settings)
    .then( res => res.json())
    .then( json => {
      return json;
    })
    .catch( e => {
      return e;
    })
  return data;
}

客户index.js

import { send } from "./lib/postRequest";

function exportEmail(data => {
    let email = JSON.stringify('exp@gmail.com')
    send({'from' : email})
})

server.js

    const express = require("express");
    const next = require("next");
    const fs = require('fs');
    const dev = process.env.NODE_ENV !== "production";
    const port = process.env.PORT || 3000;
    const ROOT_URL = dev ? "http://localhost:${port}" : "https://exp.com";

    const app = next({ dev })
    const handle = app.getRequestHandler()

    app.prepare().then(() => {
        const server = express()

        server.use(express.urlencoded({
            extended: false
        }));

        server.use(express.json());

        server.post("/send", (req, res) => {
           fs.writeFile("./temp/test.html", req.body.from, function(err) {
            if(err) {
              return console.log(err);
            }
            console.log(req.body.from)
            console.log("The file was saved!");
          });
        });

        server.get('*', (req, res) => {
            return handle(req, res)
        })

        server.listen(port, (err) => {
            if (err) throw err
            console.log('> Ready on ${ROOT_URL}')
        })

    }).catch((ex) => {
        console.error(ex.stack)
        process.exit(1)
    })

您必须设置 post 请求的正文:

const Settings = {
    method : 'POST',
    headers : {
      'Content-Type': 'application/json'
    },
    body:options
};

fetch方法中没有正文参数。 你可以这样做。

 fetch(url, {
            method: "POST", /
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(data), // body data type must match "Content-Type" header
        })
        .then(response => response.json());