简体   繁体   中英

Issue with posting data to external API using Node and Express

I am trying to post data from my form to MailChimp API server with node.js and express. However, I am getting an error message that seems strange to debug. I have checked my index.html file and all is well there. Please help me figure out a solution or point me in the right direction. Kindly check out my code below:

const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public"));
app.listen(3000, function(){

  "Server is running on Port 3000!"
});

app.get("/", function(req, res){

  res.sendFile(__dirname + "/signup.html");
});

app.post("/", function(req, res){
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
  console.log(firstName, lastName, email);

var data= {
  members: [
{
email_address : email,
status : "subscribed",
merge_fields : {
  FNAME : firstName,
  LNAME : lastName
}
}
  ]
};

var jsonData = JSON.stringify(data);
const url ="https://us10.api.mailchimp.com/3.0/lists/{apikey}";
const options = {
method: "post",
auth: "xxxx:xxxx"
}
const request= https.get(url, options, function(response){
 response.on("data", function(data){
   console.log(JSON.parse(data));
 })
})
request.write(jsonData);
request.end();

});

This is the error I am getting.


events.js:200
      throw er; // Unhandled 'error' event
      ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at write_ (_http_outgoing.js:594:17)
    at ClientRequest.write (_http_outgoing.js:586:15)
    at C:\Users\Iredafe\Desktop\Web Development practice\Email-List\app.js:48:9
    at Layer.handle [as handle_request] (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Iredafe\Desktop\Web Development practice\Email-List\node_modules\express\lib\router\index.js:275:10)
Emitted 'error' event on ClientRequest instance at:
    at writeAfterEndNT (_http_outgoing.js:649:7)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}
[nodemon] app crashed - waiting for file changes before starting...

You can use axios for simplicity.

const axios = require('axios');

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'JWT fefege...'
}

axios.post(url,postPayload,headers)
  .then(response => {
    console.log(response.data);

  })
  .catch(error => {
    console.log(error);
  });

I just found the answer. It was a bug in my code. I am using the native https method in Node hence I ought not to use https.get here:


const request= https.get(url, options, function(response){
 response.on("data", function(data){
   console.log(JSON.parse(data));
 })
})
request.write(jsonData);
request.end();

the correct code that solved the problem was using the http.request instead of http.get:

const request= https.request(url, options, function(response){
 response.on("data", function(data){
   console.log(JSON.parse(data));
 })
})
request.write(jsonData);
request.end();

Hope it helps someone in the future!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM