【发布时间】:2022-02-08 01:24:02
【问题描述】:
我在使用 POST 方法从 React 前端向 Express 后端发送 JSON 对象时遇到问题。 提交表单时出现以下错误: 从源“http://localhost:3000”访问“http://localhost:8080/create”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在 Access-Control-Allow-Origin' 标头。
任何帮助将不胜感激。由于安全隐患,我不想启用 CORS,并且在 React 项目的 package.json 中设置代理参数不起作用。
这是我的一些代码:
const handleSubmit = e => {
e.preventDefault();
if(entry !== "" && dueDate > Date.now()){
console.log({entryDate: entryDate, entry: entry, dueDate: dueDate});
axios({
method: 'post',
url: 'http://localhost:8080/create',
data: {
entryDate: entryDate,
entry: entry,
dueDate: dueDate
}
})
.then(response => response.json)
.then(data => {
console.log(`Success:: ${data}`)
})
.catch(e => {
console.log(`error: ${e}`)
})
toggle();
} else {
console.log("error")
}
}
<div>
<Modal toggle={toggle} isOpen={modal} >
<ModalHeader>Create Item</ModalHeader>
<ModalBody>
<Form>
<FormGroup>
<Label for="date">Date</Label>
<DatePicker id="entryDate" name="entryDate" onChange={onEntryDateChange} selected={entryDate}/>
</FormGroup>
<FormGroup>
<Label for="TODO">TODO</Label>
<Input type="textarea"
id="entry"
name="entry"
placeholder="Enter TODO here"
onChange={onEntryChange}/>
</FormGroup>
<FormGroup>
<Label for="dueDate">Due date</Label>
<DatePicker id="dueDate" name="dueDate"onChange={onDueDateChange} selected={dueDate}/>
</FormGroup>
</Form>
</ModalBody>
<ModalFooter>
<Button color="success" block type="submit" onClick={handleSubmit}>Create <FontAwesomeIcon icon={faPlus} size="sm"/></Button>
</ModalFooter>
</Modal>
</div>
)
}
// package.json - 我已将代理设置为 localhost:8080: ...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8080",'
...
【问题讨论】:
标签: javascript reactjs express axios