I wanted to send array of object to my mongodb DataBase, the data is Hard coated, and the file of data save as .jsx file. I make button, in which the data get and send to my dataBase, with the help of useEffect and useState, and API, But I got error when I click on it. I share complete code in which I working of:
Error when I clicked in Button
The Error showed when I click the refresh Button.
Access to XMLHttpRequest at 'http://localhost:5001/api/v1/rawData' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
POST http://localhost:5001/api/v1/rawData net::ERR_FAILED 413 Uncaught (in promise) Error:
Network Error at createError (createError.js:16:1) at XMLHttpRequest.handleError (xhr.js:117:1)
Server Code
Here is my server code, here the data schema, api written.
// import modules
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import path from "path";
import { createServer } from "http";
import { Server } from "socket.io";
import { stringToHash, varifyHash } from "bcrypt-inzi";
import jwt from "jsonwebtoken";
import cookieParser from "cookie-parser";
import postmark from "postmark";
const __dirname = path.resolve();
// making some environment setting
const SECRET = process.env.SECRET || "12345";
const POSTMARK_KEY =
process.env.POSTMARK_KEY;
const PORT = process.env.PORT || 5001;
const app = express();
let client = new postmark.ServerClient(POSTMARK_KEY);
// connect mongodb url
mongoose.connect(
"mongodb://localhost:27017/myapp"
);
const rawData = mongoose.model("Raw Data", {
created: { type: Date, default: Date.now },
allData: [{}],
});
app.use(express.json());
app.use(cookieParser());
app.use(
cors({
origin: ["http://localhost:3000", "http://localhost:5001"],
credentials: true,
})
);
app.use("/", express.static(path.join(__dirname, "web/build")));
app.get("/", (req, res, next) => {
res.sendFile(path.join(__dirname, "./web/build/index.html"));
});
// Row Data
app.get("/api/v1/rawData", (req, res) => {
rawData.findOne({})
.sort({ _id: "desc" })
.exec(function (err, data) {
res.send(data);
// console.log(data);
});
});
//path
app.use((req, res, next) => {
jwt.verify(req.cookies.token, SECRET, function (err, decoded) {
req.body._decoded = decoded;
console.log("decoded: ", decoded); // bar
if (!err) {
next();
} else {
res.status(401).sendFile(path.join(__dirname, "./web/build/index.html"));
}
});
});
// Raw Data
app.post("/api/v1/rawData", (req, res) => {
const newRawData = new rawData({
allData: req.body.allData,
});
newRawData.save().then((data) => {
console.log("Planning Data created");
res.send("Planning Data created");
});
});
app.get("/**", (req, res, next) => {
res.sendFile(path.join(__dirname, "./web/build/index.html"));
});
const server = createServer(app);
const io = new Server(server, { cors: { origin: "*", methods: "" } });
io.on("connection", (socket) => {
console.log("New client connected with id: ", socket.id);
// to emit data to a certain client
socket.emit("topic 1", "some data");
// collecting connected users in a array
// connectedUsers.push(socket)
socket.on("disconnect", (message) => {
console.log("Client disconnected with id: ", message);
});
});
server.listen(PORT, function () {
console.log("server is running on", PORT);
});
React UI Code
It is my React Js code which I use for my project
import * as React from "react";
import Button from "@mui/material/Button";
import axios from "axios";
import { myData } from "./myData";
import { useState, useEffect, useRef } from "react";
function PlanningData() {
// usestate for raw data
const [rawData, setRawData] = useState([]);
// API for setting Raw Data
useEffect(() => {
axios
.get(`${baseUrl}/api/v1/rawData`, {
withCredentials: true,
})
.then((res) => {
console.log("getRawData: ", res.data);
setRawData(res.data);
});
}, []);
// Refresh button to get the Data
const refresh = (e) => {
e.preventDefault();
axios
.post(
`${baseUrl}/api/v1/rawData`,
{
allData: myData.artical_Table,
},
{
withCredentials: true,
}
)
.then((res) => {
console.log("res: ", res.data);
});
}
return (
<div>
{/* Button for Refresh */}
<Button
onClick={refresh}
sx={{ m: 2.5 }}
style={{
display: "inline-block",
padding: "8px",
}}
size="medium"
variant="contained"
color="primary"
>
Refresh
</Button>
</div>
);
}
export default PlanningData;
myData.jsx Code
It is my Data code which I wanted to send in my Mongodb Database. This is the sample Data the actual Data was upto 40000 arrays
const myData = {
artical_Table: [
{
style_no: "Sample",
Item_description: "Sample",
mon: "10000000-0",
type: "Bags",
oq: 1,
force_update: 0,
c_n: "Sample",
pl_q: 0,
os: "Open",
},
{
style_no: "TNT-009738",
Item_description:
"Sack Bag 120x63cm Made From Cotton 100% cotton-black vat dyed 20x20/130x70 -250 GSM ? 60.5? FINISHED",
mon: "21010186-15",
type: "Bags",
oq: 200,
force_update: 2,
c_n: "SEEGLER",
pl_q: 200,
os: "Open",
},
{
style_no: "BAG-011662",
Item_description: "Police Bag Black 56x60cm",
mon: "22310008-1",
type: "Bags",
oq: 6500,
force_update: 60,
c_n: "Art Exhibition Textiles Ltd",
pl_q: 6500,
os: "Open",
},
{...},
{...},
{...},
{...},
{...},
{...},
.
.
.
{...},
],
};
export { myData };
Additionally
In addition, I wanted all datas get from external API, which is not hardcoated, but due to useState and useEffect, when my website run, my api request external API to send all the data, but I don't want to do this. I mean to say that only when I click to my refresh button then the data get from External API.
import * as React from "react";
import Button from "@mui/material/Button";
import axios from "axios";
import { useState, useEffect, useRef } from "react";
function PlanningData() {
const [arrayOfObject, setArrayOfObject] = useState([]);
useEffect(() => {
axios
.get(
`https://script.google.com/macros/s/############/exec`
)
.then((res) => {
console.log(res.data.artical_Table);
setArrayOfObject(res.data.artical_Table);
})
.catch((err) => {
alert(`Something went wrong!\n${err}`);
});
}, []);
// Refresh button to get the Data
const refresh = (e) => {
e.preventDefault();
axios
.post(
`${baseUrl}/api/v1/rawData`,
{
allData: myData.artical_Table,
},
{
withCredentials: true,
}
)
.then((res) => {
console.log("res: ", res.data);
});
}
return (
<div>
{/* Button for Refresh */}
<Button
onClick={refresh}
sx={{ m: 2.5 }}
style={{
display: "inline-block",
padding: "8px",
}}
size="medium"
variant="contained"
color="primary"
>
Refresh
</Button>
</div>
);
}
export default PlanningData;