I am trying to create an app using react native as the front end and node.js + express + mongoDB as the backend. I have no issues viewing the data from mongoDB in react native, my issue is when I try posting data to the database, every time I get the following error in both the backend and frontend.
Frontend
Here is CreatePostScreen.js
in react native:
import { create } from "apisauce";
const apiClient = create({
baseURL: "My IP Address : port number",
});
const addPost= (post) => {
const data = new FormData();
data.append("name", post.name);
data.append("title", post.title);
return apiClient.post('/post/create', data);
};
const handleSubmit = async (data) => {
const result = await addPost(data);
if (!result.ok) return alert(result.originalError);
alert("done");
};
<AppForm
initialValues={{
name: "",
title: "",
}}
onSubmit={handleSubmit}
validationSchema={validationSchema}>
<AppFormField name={"name"} placeholder="Name" />
<AppFormField name={"title"} placeholder="Title" />
<SubmitButton title={"Create Post"} />
</AppForm>
Here is the AppForm.js
component
function AppForm({ initialValues, onSubmit, validationSchema, children }) {
return (
<Formik
initialValues={initialValues}
onSubmit={onSubmit}
validationSchema={validationSchema}>
{() => <>{children}</>}
</Formik>
);
}
Here is the AppFormField.js
component
function AppFormField({ name, ...otherProps }) {
const { setFieldTouched, setFieldValue, errors, touched, values } =
useFormikContext();
return (
<>
<TextInput
onChangeText={(text) => setFieldValue(name, text)}
value={values[name]}
/>
<ErrorMessage error={errors[name]} visible={touched[name]} />
</>
);
}
Backend
Here is the postModel.js
code
const mongoose = require("mongoose");
const PostSchema = new mongoose.Schema({
name: { type: String, required: true },
title: { type: String, required: true },
});
module.exports = mongoose.model("Post", PostSchema );
Here is the postController.js
code
const Post = require("../models/postModel");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();
mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log("db connected"))
.catch((err) => console.log(err));
module.exports = {
createPost: async (req, res) => {
try {
const p = new Post(req.body);
const val = await p.save();
res.status(200).json(val);
} catch (error) {
res.status(500).json("Failed to create a new post");
}
},
Here is the postRouter.js
code
const postController = require("../controllers/postController ");
const express = require("express");
const router = express.Router();
router.use(express.urlencoded({ extended: true }));
router.use(express.json());
router.get("/", structureController.getAllStructures);
router.get("/:id", structureController.getStructure);
router.get("/search/:key", structureController.searchStructure);
router.post("/create",postController.createPost);
Here is the index.js
code
const express = require("express");
const app = express();
const postRouter = require("./routers/post");
app.use("/structures", structureRouter);
app.listen(process.env.PORT, "My IP Address", () =>
console.log(`App listening on port ${process.env.PORT}!`)
);
Errors
Here is the error that shows up in react native:
Here is the error that shows up in the backend
SyntaxError: Unexpected token 'n', "#" is not valid JSON
at JSON.parse (<anonymous>)
at createStrictSyntaxError (node_modules\express\node_modules\body-parser\lib\types\json.js:160:10)
at parse (node_modules\body-parser\lib\types\json.js:83:15)
at node_modules\body-parser\lib\read.js:128:18
at AsyncResource.runInAsyncScope (node:async_hooks:206:9)
at invokeCallback (node_modules\raw-body\index.js:231:16)
at done (node_modules\raw-body\index.js:220:7)
at IncomingMessage.onEnd (node_modules\raw-body\index.js:280:7)
at IncomingMessage.emit (node:events:514:28)
at endReadableNT (node:internal/streams/readable:1376:12)
Can anyone please assist me on how to overcome this error?