我正在尝试将电子邮件地址作为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)
})
答案 0 :(得分:0)
您必须设置帖子请求的正文:
const Settings = {
method : 'POST',
headers : {
'Content-Type': 'application/json'
},
body:options
};
答案 1 :(得分:0)
访存方法中没有body参数。 您可以这样做。
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());