fetch api makes get request instead of post

Viewed 330

i am using ReactJS and nodeJS on backend.

I'm handling submitting of form this way:

const [email, setEmail] = useState({
    name: "",
    subject: "",
    message: "",
    address: "",
  });
const sendHandler = async e => {
    e.preventDefault();
    setSending(true);
    const res = await fetch("/api/send-mail", {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(email),
    });
    ...rest of the code
  };

But somehow, when sendHandler function is executed, get request is made instead of post. P.S i'm making request from localhost to https website.

1 Answers

A quick test of your code below definitely sends a POST (which then gets a CORS error). Are you getting any errors in your console?

const email = {
    name: "",
    subject: "",
    message: "",
    address: "",
  };
const sendHandler = async e => {
    const res = await fetch("http://www.mocky.io/v2/5ec1a76e2f00006600c34d9b", {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(email),
    });
    console.log('Rest of code');
  };
  
  sendHandler(email);

Related