无法让节点快速服务器运行

时间:2021-07-28 14:40:59

标签: javascript node.js reactjs express cors

我想用 express 设置一个节点服务器来运行 nodmailer。我的前端是用 cra 构建的 - 我认为该区域没有问题。 我的问题是: 为什么我的快递服务器不能正常工作? 为什么我收到一条错误消息,告诉我“由于访问控制检查,XMLHttpRequest 无法加载 http://localhost:5000/send_mail。”? 这个脚本中的 fu&%!§g 错误在哪里?

文件夹结构看起来像这样:

  1. 后端(文件夹)
  • .env
  • index.js
  1. 前端(文件夹)
  • 公共(子文件夹)
  • src(子文件夹)
  • index.js
  • App.js
  • Mailer.js

前端有一个 package.json,后端文件夹中有一个。 在 express 应用程序中,app.listen 在控制台中工作,但是 app.get 的 console.log 不起作用,浏览器只是显示它无法连接到 localhost:5000。 >

这是我的后端/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}`);
  })
);

这是来自后端文件夹的我的 package.json

{
  "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"
  }
}

附加前端部分: 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;

感谢你们的帮助!

1 个答案:

答案 0 :(得分:-1)

CORS 阻止您发送 POST 请求,您需要将此代码添加到您的 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();
  });