【发布时间】:2022-02-01 17:31:06
【问题描述】:
我有一个使用 Reactjs-frontend、Nodejs(后端)开发的示例登录表单,我正在尝试访问 POST API 以将表单数据(用户名和密码)发布到 Nodejs API 以捕获数据并在后端处理它。 下面是我写的代码。
index.js
const express = require("express");
const cors = require("cors")
const bodyParser = require("body-parser")
const app = express();
app.use(cors({
origin: "*",
allowedHeaders: "Origin, X-Requested-With, Content-Type, Accept, Authorization",
methods: "GET, POST, PUT, PATCH, DELETE, OPTIONS"
}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())
const routesHandler = require("./routes/handler.js");
app.use("/", routesHandler)
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server is running on PORT: ${port}`));
routes/handler.js
const router = express.Router();
const { spawn } = require("child_process");
router.post("/save_args", (req, res) => {
const command_exec = spawn("python3", ["./server/login.py", req.body.user, req.body.password]);
command_exec.stdout.on("data", (data) => {
res.send(data);
});
});
module.exports = router;
PostToPython.js(ReactJs 组件)
import React, { useState } from 'react';
import axios from 'axios'
import { Button } from './Button';
export const PostToPython = () => {
const usernameRef = React.useRef();
const passwordRef = React.useRef();
const [respFromServer, setResp] = useState({"output": "", "data": ""});
const postToPython = async(e) => {
const details = {"user": usernameRef.current.value, "password": passwordRef.current.value}
e.preventDefault()
const response = await axios.post(`//${window.location.hostname}:4000/save_args`, details)
if (response.data.error){
setResp({"output": response.data.error, "data": response.data})
}
else{
setResp({"output": response.data.response, "data": response.data})
}
}
return (
<div>
<br />
<form onSubmit={postToPython}>
<label>Username: <input ref={usernameRef} required style={{
width: "5cm",
padding: "10px 20px",
boxSizing: "border-box",
border: "none",
margin: "8px 0"
}}/></label>
<br />
<label>Password: <input ref={passwordRef} required type="password" style={{
width: "5cm",
padding: "10px 20px",
boxSizing: "border-box",
border: "none",
margin: "8px 7px"
}}/></label>
<br />
<i>Try with username and password as admin, admin</i><br /><br />
{respFromServer.output.includes("Successfully") ?
<i style={{ color: "greenyellow", fontWeight: "bold" }}>
{respFromServer.output}
</i> :
<i style={{ color: "maroon", fontWeight: "bold" }}>
{respFromServer.output}
</i>
}
<br /><br />
<Button type="submit" as="button" primary round>Submit-1</Button><br />
</form>
</div>
)
}
export default PostToPython;
在本地它工作正常,但是当推送到生产环境 (Netlify) 时,它会引发 Cors 块问题,这也需要等待一段时间并引发以下错误。
甚至标头部分不显示任何响应标头以查看“Access-Control-Allow-Origin”标头;我是不是做错了什么?
【问题讨论】: