【问题标题】:Cors blocked while accessing APIsCors 在访问 API 时被阻止
【发布时间】: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”标头;我是不是做错了什么?

【问题讨论】:

    标签: node.js reactjs api cors


    【解决方案1】:

    Access-Control-Allow-Origin 标头是从服务器发送的,您的屏幕截图仅显示请求标头。

    您的问题来自 cors() 配置中指定的通配符 "*" 来源。只有非修改方法(GET、OPTIONS、HEAD...)允许使用通配符。在您的情况下(POST),应设置客户端的确切域名+端口,例如:

    app.use(cors({
      origin: "https://your-client.example.com:3000",
    }));
    

    【讨论】:

    • 我已经尝试了上述方法,但仍然出现同样的问题;当我访问 API 时也没有响应头。
    • 请问有其他解决方案吗?
    猜你喜欢
    • 2019-11-03
    • 2022-01-01
    • 2019-10-04
    • 2021-04-15
    • 2019-12-16
    • 2019-12-18
    • 2019-11-01
    • 2023-01-10
    • 2021-10-15
    相关资源
    最近更新 更多