【发布时间】:2020-09-03 18:33:22
【问题描述】:
我正在尝试学习 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 中删除代理。或者使用代理并删除 express 中的 cros。让试试这个。不要忘记重新启动服务器,react 和 express
-
@prasanth,我更新了我的问题以显示从 React package.json 中删除代理后的新错误。现在我被拒绝连接。我不确定我在 React fetch 调用和 Express get 调用中是否正确设置了我的 url。
-
你的fetch发送
post请求。但你的快递只有app.get('/'。所以请添加app.post路由 -
@prasanth,我不确定如何编写 app.post 方法。我将不得不对此进行研究。任何帮助或解释将不胜感激。
-
检查我的答案
标签: javascript reactjs express cors