简体   繁体   中英

Why are my POST and PUT requests from Node/Express not working in React/Redux? My GET and DELETE requests all work fine. All requests work in Postman

So, I have the issue that everything works in Postman and my GET and DELETE requests even work in the full-stack program (Node/Express, React/Redux/Hooks, Microsoft SQL Server), but my POST and PUT requests are not working. As you can see in the image below, I have 403 errors and those lines are from "console.log(data);", not my error handler/catcher, so it is a "good" request, but something is not authorizing. Console logs and service file to show that data is passing, but not being accepted can be viewed here.

I have tried many, many solutions and much research. As far as I understand, this COULD be an issue with CORS, but I'm really not sure. Also, in Redux DevTools, it does not show my "UPDATE_DEVICE" OR "CREATE_DEVICE" actions, so I know that they are not even being accepted.

Here is code from AddDevice:

import { useDispatch } from "react-redux";
import { createDevice } from "../actions/devices";

const AddDevice = () => {
    const initialDeviceState = {
        id: null,
        title: "",
        detail: "",
        published: false
    };
    const [device, setDevice] = useState(initialDeviceState);
    const [submitted, setSubmitted] = useState(false);

    const dispatch = useDispatch();

    const handleInputChange = event => {
        const { name, value } = event.target;
        setDevice({ ...device, [name]: value });
    };

    const saveDevice = () => {
        const { title, detail } = device;

        dispatch(createDevice(title, detail))
            .then(data => {
                setDevice({
                    id: data.id,
                    title: data.title,
                    detail: data.detail,
                    published: data.published
                });
                setSubmitted(true);

                console.log(data);
            })
            .catch(e => {
                console.log(e);
            });
    };

    const newDevice = () => {
        setDevice(initialDeviceState);
        setSubmitted(false);
    };

    return (
        <div className="submit-form">
            {submitted ? (
                <div>
                    <h4>You submitted successfully!</h4>
                    <button className="btn btn-success" onClick={newDevice}>
                        Add
                    </button>
                </div>
            ) : (
                <div>
                    <div className="form-group">
                        <label htmlFor="title">Title</label>
                        <input
                            type="text"
                            className="form-control"
                            id="title"
                            required
                            value={device.title}
                            onChange={handleInputChange}
                            name="title"
                        />
                    </div>

                    <div className="form-group">
                        <label htmlFor="detail">Detail</label>
                        <input
                            type="text"
                            className="form-control"
                            id="detail"
                            required
                            value={device.detail}
                            onChange={handleInputChange}
                            name="detail"
                        />
                    </div>

                    <button onClick={saveDevice} className="btn btn-success">
                        Add
                    </button>
                </div>
            )}
        </div>
    );
};

export default AddDevice;

And here is from my code for updating the device:

useEffect(() => {
        getDevice(props.match.params.id);
    }, [props.match.params.id]);

    const handleInputChange = event => {
        const { name, value } = event.target;
        setCurrentDevice({ ...currentDevice, [name]: value });
    };

    const updateStatus = status => {
        const data = {
            id: currentDevice.id,
            title: currentDevice.title,
            detail: currentDevice.detail,
            published: status
        };

        dispatch(updateDevice(currentDevice.id, data))
            .then(response => {
                console.log(response);

                setCurrentDevice({ ...currentDevice, published: status });
                setMessage("The status was updated successfully!");
            })
            .catch(e => {
                console.log(e);
            });
    };

    const updateContent = () => {
        dispatch(updateDevice(currentDevice.id, currentDevice))
            .then(response => {
                console.log(response);
                setMessage("The device was updated successfully!");
                props.history.push("/devices");
            })
            .catch(e => {
                console.log(e);
            });
    };

    const removeDevice = () => {
        dispatch(deleteDevice(currentDevice.id))
            .then(() => {
                props.history.push("/devices");
            })
            .catch(e => {
                console.log(e);
            });
    };

    return (
        <div>
            {currentDevice ? (
                <div className="edit-form">
                    <h4>Device</h4>
                    <form>
                        <div className="form-group">
                            <label htmlFor="title">Title</label>
                            <input
                                type="text"
                                className="form-control"
                                id="title"
                                name="title"
                                value={currentDevice.title}
                                onChange={handleInputChange}
                            />
                        </div>
                        <div className="form-group">
                            <label htmlFor="detail">Detail</label>
                            <input
                                type="text"
                                className="form-control"
                                id="detail"
                                name="detail"
                                value={currentDevice.detail}
                                onChange={handleInputChange}
                            />
                        </div>

                        <div className="form-group">
                            <label>
                                <strong>Status:</strong>
                            </label>
                            {currentDevice.published ? "Published" : "Pending"}
                        </div>
                    </form>

                    {currentDevice.published ? (
                        <button
                            className="m-3 btn btn-sm btn-danger"
                            onClick={() => updateStatus(false)}
                        >
                            UnPublish
                        </button>
                    ) : (
                        <button
                            className="m-3 btn btn-sm btn-danger"
                            onClick={() => updateStatus(true)}
                        >
                            Publish
                        </button>
                    )}

                    <button className="m-3 btn btn-sm btn-danger" onClick={removeDevice}>
                        Delete
                    </button>

                    <button
                        type="submit"
                        className="btn btn-success"
                        onClick={updateContent}
                    >
                        Update
                    </button>
                    <p>{message}</p>
                </div>
            ) : (
                <div>
                    <br />
                    <p>Please click on a device.</p>
                </div>
            )}
        </div>
    );
};

export default Device;

And finally, this is my server.js code from back-end:

var express = require('express');
var bodyParser = require('body-parser');
const cors = require("cors");

var app = express();

var corsOptions = {
    origin: "http://localhost:8083"
};

app.use(cors(corsOptions));
app.use(express.json());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));

const db = require('./app/config/db.config');

const Role = db.role;

db.sequelize.sync();
// db.sequelize.sync({ force: true }).then(() => {
// console.log("Drop and re-sync db.");
// initial();
// });
// CODE ABOVE MAY BE NECESSARY FOR DATABASE TESTING, ESPECIALLY IF DATABASE MIGRATION OCCURS BECAUSE THE "initial" FUNCTION ESTABLISHES ROLES, WHICH IS CRUCIAL

require("./app/router/router.js")(app);

var server = app.listen(3000, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("App listening at http://%s:%s", host, port)
})

function initial(){
    Role.create({
        id: 1,
        name: "USER"
    });

    Role.create({
        id: 2,
        name: "ADMIN"
    });

    Role.create({
        id: 3,
        name: "PM"
    });
}

The repositories are here ( https://github.com/vaahtlnirn1 ; my only two public repositories) for your viewing pleasure, but I wouldn't think that there's something wrong beyond these files. I have a feeling that the solution is something very stupid and small, as data is properly being passed and all, but I have been stuck on this for about 2 hours now and have tried many solutions and couldn't find my answer from other similar questions in here. Help is highly appreciated!

发送请求格式错误。

axios.post (url, data, {...headers here})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM