首页 > 解决方案 > 反应/快速访问以从 CORS 策略阻止的 Origin 获取

问题描述

我正在尝试学习 React 和 Express。我正在尝试允许从反应组件上传本地文件,并且需要 Express 来捕获文件,但无论我尝试什么,我都会得到:

Access to fetch at 'http://localhost:3001/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我已经在 Express 服务器上安装了 npm install CORS --save。我在 React package.json 中设置了一个代理。见下文:

},
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "proxy": "http://localhost:3001",
  "browserslist": {

React 在端口 3000 上运行,Express 在 3001 上运行。

这是执行 fetch 的组件:

import React, { Component } from 'react';

class AddNewItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedFile: null,
      imagePath: ''
    }
  }

  handleSubmit = (event) => {
    event.preventDefault()
    console.log(event.target[0].value)
    console.log(event.target.title.value)
    console.log(event.target.image.value)
    console.log(this.inputNode.value)

    const data = new FormData()
    data.append("image", this.state.selectedFile)

    //const myFileInputs = document.querySelector("input[type='image']");

    fetch('http://localhost:3001', {
      method: 'POST',
      body: data
    })
      .then(response => response.json())
      .then(data => {
        console.log(data)
        this.setState({ fileName: data.originalname })
      })
  }

  fileSelectedHandler = event => {
    console.log(event.target.files[0]);

    this.setState({
      selectedFile: event.target.files[0],
      loaded: 0,
    })
  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>Title:</label><br />
          <input type="text" id="title" name="title" ref={node => (this.inputNode = node)} /><br />
          <label>Image:</label><br />
          <input type="file" id="image" name="image" onChange={this.fileSelectedHandler}></input>
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}

export default AddNewItem;

这是我的 Express 服务器:

var express = require('express')
var cors = require('cors')
var app = express()

var whitelist = ['http://localhost:3000']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.get('/', cors(corsOptions), function (req, res, next) {
  res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' })
})

app.listen(3001, function () {
  console.log('CORS-enabled web server listening on port 3001')
})

当我启动 Express 服务器时,我得到

CORS-enabled web server listening on port 3001

在我的终端。

当我将文件从 React 组件提交到 Express 服务器时,我的网页控制台会给出以下输出。看屏幕截图: 在此处输入图像描述

我究竟做错了什么?我已经为此工作了几个小时。谢谢。

从 React package.json 中删除代理后,我在控制台中得到以下信息: 在此处输入图像描述

标签: javascriptreactjsexpresscors

解决方案


与其中任何一个一起做。

  1. 从中删除代理package.json
  2. 使用代理并cors从快递中删除

您的 fetch 发送一个method:'POST'post 请求。但你的快递只有get要求。所以你应该post像这样在快递上添加路线

POST 路线 文档

app.post('/', cors(corsOptions), function (req, res, next) {
  res.json({ msg: 'This is CORS-enabled for a whitelisted domain POST request' })
})

推荐阅读