简体   繁体   English

带有 axios 的 Nodemon 服务器 - 无法发送

[英]Nodemon server with axios - Unable to Send

I have a React app and within this app a folder called backend.我有一个 React 应用程序,在这个应用程序中有一个名为 backend 的文件夹。 This folder contains 2 files:该文件夹包含 2 个文件:

在此处输入图片说明

Config contains a variable with email and password through nodemailer. Config 通过 nodemailer 包含一个带有电子邮件和密码的变量。 Index.js (which is what my server is supposed to run) has this: Index.js(这是我的服务器应该运行的)有这个:

const path = require("path");
const express = require("express");
const transporter = require("./config");
const dotenv = require("dotenv");
dotenv.config();
const app = express();

const buildPath = path.join(__dirname, "..", "build");
app.use(express.json());
app.use(express.static(buildPath));

app.post("/send", (req, res) => {
  try {
    const mailOptions = {
      from: req.body.email, // sender address
      to: process.env.email, // list of receivers
      subject: req.body.subject, // Subject line
      html: `
      <p>You have a new contact request.</p>
      <h3>Contact Details</h3>
      <ul>
        <li>Name: ${req.body.name}</li>
        <li>Email: ${req.body.email}</li>
        <li>Subject: ${req.body.subject}</li>
        <li>Message: ${req.body.message}</li>
      </ul>
      `,
    };

    transporter.sendMail(mailOptions, function (err, info) {
      if (err) {
        res.status(500).send({
          success: false,
          message: "Something went wrong. Try again later",
        });
      } else {
        res.send({
          success: true,
          message: "Thanks for contacting us. We will get back to you shortly",
        });
      }
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: "Something went wrong. Try again later",
    });
  }
});

app.listen(3030, () => {
  console.log("server start on port 3030");
});

Then, within a different folder (components) I have a component file that takes the form information and it's supposed to take it to the server:然后,在不同的文件夹(组件)中,我有一个组件文件,它接收表单信息,并且应该将其传送到服务器:

import React, { useState } from "react";
import axios from "axios";
import { Form, Button } from "react-bootstrap";
import Navbar from "../components/Navbar";
import BottomNav from "../components/BottomNav";

const Contact = () => {
  const [state, setState] = useState({
    name: "",
    email: "",
    subject: "",
    message: "",
  });

  const [result, setResult] = useState(null);

  const sendEmail = event => {
    event.preventDefault();
    axios
      .post("/send", { ...state })
      .then(response => {
        setResult(response.data);
        setState({
          name: "",
          email: "",
          subject: "",
          message: "",
        });
      })
      .catch(() => {
        setResult({
          success: false,
          message: "Something went wrong. Try again later",
        });
      });
  };

  const onInputChange = event => {
    const { name, value } = event.target;

    setState({
      ...state,
      [name]: value,
    });
  };

  return (
    <div>
      <Navbar />
      {result && (
        <p className={`${result.success ? "success" : "error"}`}>
          {result.message}
        </p>
      )}
      <form
        className="phs-form-wrapper mt-8 h-screen flex flex-col items-center "
        onSubmit={sendEmail}
      >
        <Form.Group
          className=" phs-form-group flex flex-col items-center"
          controlId="name"
        >
          <Form.Label className="phs-form-label mr-2">Full Name</Form.Label>
          <Form.Control
            type="text"
            name="name"
            value={state.name}
            onChange={onInputChange}
          />
        </Form.Group>
        <Form.Group
          className=" phs-form-group flex flex-col items-center"
          controlId="email"
        >
          <Form.Label className="phs-form-label mr-2">Email</Form.Label>
          <Form.Control
            type="text"
            name="email"
            value={state.email}
            onChange={onInputChange}
          />
        </Form.Group>
        <Form.Group
          className=" phs-form-group flex flex-col items-center"
          controlId="subject"
        >
          <Form.Label className="phs-form-label mr-2">Subject</Form.Label>
          <Form.Control
            type="text"
            name="subject"
            value={state.subject}
            onChange={onInputChange}
          />
        </Form.Group>
        <Form.Group
          className=" phs-form-group flex flex-col items-center"
          controlId="subject"
        >
          <Form.Label className="phs-form-label mr-2">Message</Form.Label>
          <Form.Control
            as="textarea"
            name="message"
            value={state.message}
            rows="3"
            onChange={onInputChange}
          />
        </Form.Group>
        <Button
          className="phs-form-submit-button bg-black text-white p-4 mt-4"
          variant="primary"
          type="submit"
        >
          Submit
        </Button>
      </form>
      <BottomNav />
    </div>
  );
};

export default Contact;

I am getting an error on both servers.我在两台服务器上都收到错误消息。 On localhost:3000 which is where I run my react app whenever I try to submit the info I get a:在 localhost:3000 上,每当我尝试提交信息时,我都会运行我的反应应用程序,我得到:

VM635:1 POST http://localhost:3000/send 404 (Not Found)

On localhost:3030:在本地主机上:3030:

GET http://localhost:3030/ 404 (Not Found)
localhost/:1 Refused to load the image 'http://localhost:3030/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.

I note that my axios has a .post("/send") but I tried to change this to localhost:3030/send and doesn't work either.我注意到我的 axios 有一个 .post("/send") 但我试图将其更改为 localhost:3030/send 并且也不起作用。

Additionally I have 2 package.json files, one within my react folder (web) and another one within my backend folder.此外,我有 2 个 package.json 文件,一个在我的 react 文件夹(web)中,另一个在我的后端文件夹中。

The backend one has a script like this:后端有一个这样的脚本:

"scripts": {
    "dev": "nodemon src/index.js"
  }

The web one has a different script so I run a different server:网络有一个不同的脚本,所以我运行不同的服务器:

"scripts": {
    "start": "npm run watch:css && react-scripts start",
    "build": "npm run watch:css && react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "watch:css": "postcss src/assets/tailwind.css -o src/assets/main.css"
  }

Any ideas?有任何想法吗?

When you're running both the backend and frontend servers on different ports (:3000 and :3030 in this case), you need to particularly mention the whole url in axios call.当您在不同的端口上运行后端和前端服务器时(本例中为 :3000 和 :3030),您需要特别提及 axios 调用中的整个 url。 In this case, /send is considered as http://localhost:3000 where the POST method doesn't exists (The reason why you're getting 404).在这种情况下, /send被视为http://localhost:3000 ,其中 POST 方法不存在(您得到 404 的原因)。 You must make the following axios call:您必须进行以下 axios 调用:

const sendEmail = event => {
    event.preventDefault();
    axios
      .post("http://localhost:3030/send", state, {
        headers: { 
         'Access-Control-Allow-Origin' : '*'
        },
      })
      .then(response => {
        ...
      })
      .catch(() => {
        ...
      });
  };

Also you don't need to spread the state in axios call.此外,您不需要在 axios 调用中传播状态。 The reason is axios call accepts second argument as object.原因是 axios 调用接受第二个参数作为对象。

On your react app try sending it to "http://localhost:3030/send" instead "/send".在您的 React 应用程序上,尝试将其发送到“http://localhost:3030/send”而不是“/send”。 I believe its because your server URL and your react dev server URL are different when you run it locally我相信这是因为在本地运行时,您的服务器 URL 和 react dev 服务器 URL 不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM