javascript - 反应/快速访问以从 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 服务器时,我的网页控制台会给出以下输出。看屏幕截图:
我究竟做错了什么?我已经为此工作了几个小时。谢谢。
解决方案
与其中任何一个一起做。
- 从中删除代理
package.json
- 或使用代理并
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' })
})
推荐阅读
- react-native - 世博会图标显示为问号 (?)
- python - 修复条形图matplotlib的标注功能
- python - 使用 Python 从基于 Topic 的文本中提取关键短语
- python - 带有 Anaconda 的 VSCode 在终端中的运行中找到模块,但在运行代码或调试器中找不到
- javascript - 我如何在javascript中开始一个新行
- ios - 如何使用 UIDocumentInteractionController 将视频文件保存到 iOS 文件应用程序
- java - JScrollPane 中的 JPanel 不会动态调整大小
- angular - 角度将日期时间设置为本地时间
- flask - 如何解决 Heroku 上缺少的模块 Tweepy?
- html - Django 模板。我想将一个视图查询显示为两列