我正在尝试学习React和Express。我正在尝试允许从react组件上载本地文件,并且需要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上运行。
这是执行提取的组件:
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
在我的终端上。
My web page console gives me the following output when I submit the file to the Express server from the React component. See the screen shot:
我究竟做错了什么?我已经为此工作了几个小时。谢谢。