简体   繁体   中英

How to fix Fetch request to Node.js server?

I'm trying to do a simple POST request using fetch. I'm trying to create a contact form using Vanilla Javascript, HTML, CSS on the front end and Node.js / Express on the backend. Here's my front end code:

            <form id="sendMail">
                <div>
                  <label for="name">Name: </label>
                  <input name="name" id="name" placeholder="Name">
                </div>
                <div>
                  <label for="email">Email: </label>
                  <input name="email" id="email" placeholder="Email">
                </div>
                <div>
                    <label for="phone">Phone: </label>
                    <input name="phone" id="phone" placeholder="Phone">
                  </div>
                <div>
                    <label for="subject">Message: </label>
                    <input name="subject" id="subject" placeholder="How can we help you?">
                </div>
                <div>
                  <input type="submit">Send Message</input>
                </div>
            </form> 

<script>
  document.getElementById("sendMail").addEventListener('submit', sendMail);

  function sendMail(e) {
    e.preventDefault();

    let name = document.getElementById("name").value;
    let email = document.getElementById("email").value;
    let phone = document.getElementById("phone").value;
    let subject = document.getElementById("subject").value;

    console.log("sendMail fired!", name, email, phone, subject);

    fetch('/api/contact', {
        method: 'POST', 
        headers: {
          'Accept': 'application/json, text/plain, */*',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({name: name, email: email, phone: phone, subject: subject}),
      })
    //   .then(response => response.json())
      .then(data => {
        console.log('Success:', data);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  } 
</script>   

Here is my code on the backend:

const http = require('http');
const express = require('express');
const path = require('path');
const cors = require('cors');

const app = express();

app.use(cors());
app.use(express.json());
app.use(express.static("express"));

// default URL for website
app.use('/', function(req,res){
    res.sendFile(path.join(__dirname+'/express/index.html'));
    //__dirname : It will resolve to your project folder.
  });

const server = http.createServer(app);
const port = 4040;

const nodemailer = require('nodemailer');

app.post('/api/contact', async(req, res, next) => {
  const { name, email, phone, subject } = req.body;
  console.log("sendMail fired: ", req.body, name, email, phone, subject);

  const transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
          user: 'myEmailAddress',
          pass: 'myPassword',
      }
  });

  let mailOptions = await transporter.sendMail({
      from: `info@companyemailaddress`,
      to: `${email}`,
      subject: `company`,
      text:
          `${name}, \n\n` +
          `Thank you for contacting company! A representative will contact you within 2 business days. \n\n` +
          `If you have any further question, feel free to email us at:  \n\n` +
          `info@company \n\n` +
          `- company Automated Message`
  });

  console.log('Message sent: %s', mailOptions.messageId);
  // console.log('Preview URL: %s', nodemailer.getTestMessageUrl(mailOptions))

  let mailOptions2 = await transporter.sendMail({
    from: `info@companyemail address`,
    to: `myEmail`,
    subject: `company`,
    text:
        `Name: ${name}, \n\n` +
        `Email: ${email}, \n\n` +
        `Phone: ${phone}, \n\n` +
        `Subject: ${subject}, \n\n`
  });

  console.log('Message sent: %s', mailOptions2.messageId);

  res.send('Email sent!')   
})


server.listen(port);

console.debug('Server listening on port ' + port);

When I click the "submit" input on the front end, I get a successful response without any server error messages, but when I look at my server console.logs, it shows nothing - as if the server has not been touched. If I just send an object in the body of the post request that is not JSON.stringify(), the server DOES give error messages saying that there's an issue with the object in the body. So it looks like the POST request is successfully contacting the server. But nothing happens.

What am I doing wrong?

You should change your root route from app.use to app.get

when you use app.use on / it matches any routes with any http verb and acts as a global middleware .

Therefore your post request was actually getting matched by that app.use & your actual app.post never got chance to execute.

You can test yor api with postman then generate the fetch request for you. in your case you should put the full uri as args to your fetcch call.

fetch('http://example.com/movies.json')

.then(response => response.json()).then(console.log);

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