我正在尝试通过在 hyper shell 上使用 mailchimp API 来使用 NodeJS 和 Express 制作 newsLetter 服务。我已经安装了所有必要的东西,包括 npm、express、request、https 模块。代码工作正常,直到我尝试在 mailChimp 服务器中写入用户信息并向我显示 typeError 消息:request.write() 不是函数。下面是我的代码和我的错误代码的快照。
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function (req, res) {
const firstName = req.body.fname;
const lastName = req.body.lname;
const email = req.body.email;
const password = req.body.pass;
const cPassword = req.body.cPass;
//console.log(firstName);
//res.send(firstName);
var data = {
members: [
{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}
]
};
const jsonData = JSON.stringify(data);
const url = "https://us1.api.mailchimp.com/3.0/lists/97d15bb1ff";
const options = {
method: "POST",
auth: "Mr.M:d2f2f965b9e6b751a305bb6ce2ad7ed4-us1",
};
https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end();
//res.send("hey")
});
app.listen(3000, function () {
console.log("Server is running at port 3000");
});
答案 0 :(得分:0)
使用上面的代码代替 request.write(jsonData), request.end().
答案 1 :(得分:0)
https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
}); });
改为使用这个:
const request = https.request(url, options, function (response) {
response.on("data", function (data) {
console.log(JSON.parse(data));
});
});
答案 2 :(得分:0)
正如 Lingyu Kong 已经指定的,您需要将您的请求保存在一个常量变量中,以便您以后调用它:
下面的 node.js 网站链接完美地说明了这一点:
https://nodejs.org/api/http.html#http_http_request_url_options_callback