jen007
jen007

Reputation: 1599

Pass data from react component to proxy(node server)

I set up a proxy to bypass CORS for the intended api in this react application. I'm having trouble to pass data from react component to proxy(nodeJS server). I've read a few links such as here and here but still have no clues.

/*React component*/
import React, { useState } from "react";
import axios from "axios";

export default function Mail() {
  const [emailInput, setEmailInput] = useState('')
  const getMail = () => {
    axios.get("/list/members").then(json => {
      console.log(json.data);
    });
  };

  const subscribe = (email) => {
    console.log('inside subscribe')
    axios.post("/member", email)
    .then(data => console.log('post succeeds'))
    .catch(err => console.log(err))
  }

  const handleSubmit = e => {
    e.preventDefault();

    const email = {
      email_address: `${emailInput}`,
      status: "subscribed"
    };

    subscribe(email)
  };

  const handleChange = (e) => {
    setEmailInput(e.target.value)
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="email" placeholder="enter your email" value={emailInput} onChange={handleChange}/>
      <input type="submit" value="subscribe" />{" "}
    </form>
  );
}

In node server, I have

app.post("/member", (req, res) => {
  const email = {
    email_address: "[email protected]",
    status: "subscribed"
  };

  axios.post(
    "https://<apilink>",
    email,
    {
      withCredentials: true,
      auth: {
        username: "anystring",
        password: "<apikey>"
      }
    }
  ).then(json => {
    res.send(json.data)
  }).catch(err => {
    console.log(err);
  })
});

I've checked that my conduit between react front end app and proxy server is working. I also examined both req and res in app.post("/member", (req, res) but found thatreq.body is undefined and couldn't find the email object that was passed in from react function component. Did I miss anything here?

Upvotes: 0

Views: 298

Answers (1)

Kieran Quinn
Kieran Quinn

Reputation: 1115

Are you using a body-parser? If not, install body-parser and then change your code to this:

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post("/member", (req, res) => {
  const email = req.body.email_address;

  axios.post(
    "https://<apilink>",
    email,
    {
      withCredentials: true,
      auth: {
        username: "anystring",
        password: "<apikey>"
      }
    }
  ).then(json => {
    res.send(json.data)
  }).catch(err => {
    console.log(err);
  })
});

Upvotes: 1

Related Questions