从React前端到Express后端建立代理连接时出现问题



我在使用POST方法将JSON对象从React前端发送到Express后端时遇到问题。我在提交表格时出现以下错误:访问'XMLHttpRequesthttp://localhost:8080/create'来自原点'http://localhost:3000'已被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",'

SOLVED
我最终使用了axios.post函数,该函数的url字符串不包括localhost:8080。由于它已经在package.json文件中指定了代理url,所以在使用axios进行后期调用时,我不必再这样做了。

这是更新后的代码:

axios
.post('/create', data)
.then((response) => response.json)
.then((data) => {
console.log(`Success:: ${data}`);
})
.catch((e) => {
console.log(`error: ${e}`);
});

无论如何,谢谢!

最新更新