简体   繁体   中英

Can´t get node express server to run

I want to setup a node server with express to run nodmailer. My frontend is builded with cra - I think there are no problems in that zone. My questions are: Why does my express server doesnt work right? Why do I get an error telling me 'XMLHttpRequest cannot load http://localhost:5000/send_mail due to access control checks.'? Where is the fu&%!§g error in this script?

The folder structure does looks like that:

  1. backend (folder)
  • .env
  • index.js
  1. frontend (folder)
  • public (subfolder)
  • src (subfolder)
  • index.js
  • App.js
  • Mailer.js

There is one package.json in the frontend and one in the backend folder. In the express application app.listen works in console, but console.log of app.get doesnt work and browser just shows that it cant connect to localhost:5000.

Here is my backend/ index.js :

const express = require('express');
const dotenv = require('dotenv');
const cors = require('cors');
const nodemailer = require('nodemailer');

const app = express();
require('dotenv').config();

const PORT = process.env.PORT || 5000;

app.use(cors());

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.get('/', (req, res) => {
  console.log(`this text should be visible in browser`);
  res.send('API is running...');
});

app.post('/send_mail', cors(), async (req, res) => {
  let { text } = req.body;
  const transport = nodemailer.createTransport({
    host: process.env.MAIL_HOST,
    port: process.env.MAIL_PORT,
    auth: {
      user: process.env.MAIL_USER,
      pass: process.env.MAIL_PASS,
    },
  });

  await transport.sendMail({
    from: `${email}`,
    to: 'test@test.com',
    html: `<div className="email">
        <h2>Here is your email!</h2>
        <p>${text}</p>
         </div>
    `,
  });
});

app.listen(
  (PORT,
  () => {
    console.log(`Server is listening on port ${PORT}`);
  })
);

and here is my package.json from backend folder:

{
  "name": "backend",
  "version": "1.0.0",
  "description": "react contact form backend server",
  "main": "index.js",
  "scripts": {
    "watch": "nodemon ./index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Itsme",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "nodemailer": "^6.6.3",
    "nodemon": "^2.0.12"
  }
}

Additional the frontend part: Mailer.js:

import axios from 'axios';
import React, { useState } from 'react';

const Mailer = () => {
  const [sent, setSent] = useState(false);
  const [text, setText] = useState('');

  const handleSend = async (e) => {
    setSent(true);
    try {
      await axios.post('http://localhost:5000/send_mail', {
        text,
      });
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <div className='Mailer'>
      {!sent ? (
        <form onSubmit={handleSend}>
          <input
            type='text'
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
          <button type='submit'>Send</button>
        </form>
      ) : (
        <h3>Thanks for your message</h3>
      )}
    </div>
  );
};

export default Mailer;

App.js:

import './App.css';
import Mailer from './Mailer';

function App() {
  return (
    <div className='App'>
      <Mailer />
    </div>
  );
}

export default App;

Thanks for your help guys!

CORS is blocking u from sending an POST request, U need to add this code to your index.js:

 app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); });

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