【问题标题】:How to fix cross origin errors use React & Express API如何使用 React 和 Express API 修复跨源错误
【发布时间】:2020-08-05 01:45:32
【问题描述】:

我在带有节点的 React 和 Express API 中有一个简单的联系表单,但是每次我填写表单并单击提交按钮时都会收到此错误:

Access to XMLHttpRequest at 'localhost:4000/api/v1/' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
App.js:33 Message not sent
xhr.js:178 POST localhost:4000/api/v1/ net::ERR_FAILED

我的 App.js 看起来像:

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


class Contact extends Component {

    state = {
        name: '',
        message: '',
        email: '',
        sent: false,
        buttonText: 'Send Message'
    }

    formSubmit = (e) => {
        e.preventDefault()

        this.setState({
            buttonText: '...sending'
        })

        let data = {
            name: this.state.name,
            email: this.state.email,
            message: this.state.message,
            username: this.state.username,
            password: this.state.password
        }

        axios.post("localhost:4000/api/v1/", data)
        .then( res => {
            this.setState({ sent: true }, this.resetForm())
        })
        .catch( () => {
          console.log('Message not sent')
        })
      }

      resetForm = () => {
        this.setState({
            name: '',
            message: '',
            email: '',
            buttonText: 'Message Sent'
        })
    }

    render() {
        return(
          <form className="contact-form" onSubmit={ (e) => this.formSubmit(e)}>
          <label className="message" htmlFor="message-input">Your Message</label>
          <br/>
          <textarea onChange={e => this.setState({ message: e.target.value})} name="message" className="message-input" type="text" placeholder="Please write your message here" value={this.state.message} required/>
          <br/>
          <label className="message-name" htmlFor="message-name">Your Name</label>
          <br/>
          <input onChange={e => this.setState({ name: e.target.value})} name="name" className="message-name" type="text" placeholder="Your Name" value={this.state.name}/>
          <br/>
          <label className="message-email" htmlFor="message-email">Your Email</label>
          <br/>
          <input onChange={(e) => this.setState({ email: e.target.value})} name="email" className="message-email" type="email" placeholder="your@email.com" required value={this.state.email} />

          <div className="button--container">
              <button type="submit" className="button button-primary">{ this.state.buttonText }</button>
          </div>
        </form>
        );
    }
}

export default Contact;

我的 Api.js 看起来像这样:

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

const port = 4000;

app.use(cors());

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

app.listen(port, () => {
  console.log('We are live on port 4000');
});

app.get('/', (req, res) => {
  res.send('Welcome to my api');
})

app.post('/api/v1', (req,res) => {
  const { body: { username, password }} = req;
  const params = req.params;
  console.log(params)
  var data = req.body;

var smtpTransport = nodemailer.createTransport({
  service: 'Gmail',
  port: 465,
  auth: {
    user: 'pizhevsoft@gmail.com',
    pass: 'pass123'
  }
});

var mailOptions = {
  from: data.email,
  to: 'pizhevsoft@gmail.com',
  subject: 'New Request',
  html: `<p>${data.name}</p>
          <p>${data.email}</p>
          <p>${data.message}</p>`
};

smtpTransport.sendMail(mailOptions,
(error, response) => {
  if(error) {
    res.send(error)
  }else {
    res.send('Success')
  }
  smtpTransport.close();
});
})

在控制台中,我在 Chrome 的 cors 上看到了一个错误,然后我在控制台中看到了“消息未发送”状态。我不确定这段代码是否正常工作。但我需要先清除这个错误才能继续前进。

我可以举一些例子来解决这个错误吗:(?

【问题讨论】:

  • 嗨,把“app.use(cors())”放在api.js文件中的所有中间件之上
  • 我将 app.use(cors()) 移到中间件之后的顶部,但收到错误消息:
  • ReferenceError: 初始化前无法访问“应用程序”
  • const app = express(); app.use(cors());常量端口 = 4000;但是错误是一样的..
  • 能否更新问题中的代码

标签: node.js reactjs api express


【解决方案1】:

你打的是/api/v1而不是/api/v1/:user/:pass

将路由更改为/api/v1,并在请求正文中发送用户名和密码。

app.post('/api/v1', (req, res) =&gt; {...}

不要在参数中发送敏感信息。它将显示在您的浏览器历史记录和其他日志中。

formSubmit = (e) => {
   //code
   const data = {
     name: this.state.name,
     email: this.state.email,
     message: this.state.message,
     username: this.state.username,
     password: this.state.password
   }
   //code
}
app.post('/api/v1', (req,res) => {
   const { body: { username, password }} = req;
   ...
}

【讨论】:

  • 你能给我这个代码的完整例子吗..如何移动用户名并在正文中传递?
  • 我已经添加了示例。看看@PizhevRacing
  • 谢谢你,我会尽力给你反馈:D
  • 我不确定这段代码中发生了什么:app.post('/api/v1', (req,res) => { const { body: { username, password }} = req; const params = req.params; console.log(params) var data = req.body; var smtpTransport = nodemailer.createTransport({ service: 'Gmail', 端口: 465, auth: { user: 'pizhevsoft@gmail.com' , 通过: 'pass123' } });
  • 将 app.listen() 移到底部
猜你喜欢
  • 1970-01-01
  • 2021-04-01
  • 2018-06-28
  • 2022-01-20
  • 2021-05-28
  • 1970-01-01
  • 2022-12-30
  • 1970-01-01
  • 2019-07-19
相关资源
最近更新 更多