(I know this has a bad title)
I’m using firebase and express for this project but this doesn’t work.
src/index.js
import { initializeApp } from "firebase/app";
import { doc, getFirestore } from "firebase/firestore";
import { collection, addDoc, getDoc } from "firebase/firestore";
import Chance from "chance";
import express from 'express';
import bodyParser from 'body-parser';
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var chance = new Chance();
const expressApp = express();
expressApp.set('view engine', 'ejs');
expressApp.get('/', (req, res) => {
console.log("hello");
res.render('index');
});
expressApp.post('/add', jsonParser, (req, res) => {
add(req.body.name);
res.send(`You said ${req.body.name}`);
res.status(200);
});
const firebaseConfig = {
apiKey: "apikey",
authDomain: "authDomain",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appId",
measurementId: "measurementId"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
async function add(firstName) {
try {
const docRef = await addDoc(collection(db, "users"), {
first: firstName,
last: chance.last(),
born: chance.year({ min: 1920, max: 2000 }),
},);
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
}
expressApp.listen(3000);
//add();
(Everything in the firebase config is actually there in my real js file)
src/views/index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<input id="input" type="text" />
<button>Submit</button>
</body>
<script>
document.querySelector("button").addEventListener("click", function () {
const input = document.getElementById("input");
fetch("/add", {
method: "post",
body: {
name: input.value,
},
})
.then((response) => response.json())
.then((data) => console.log(data));
});
</script>
</html>
In my terminal I’m getting this error
Error adding document: [FirebaseError: Function addDoc() called with invalid data. Unsupported field value: undefined (found in field first in document users/VI9jpmKrASca4PhrTxYC)] {
code: ‘invalid-argument’,
customData: undefined,
toString: [Function (anonymous)] }
and in my console(firefox) Im getting this
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
also if I use insomnia or rest clinet and pass in an object like
{
"name":"hello",
}
it works properly
2
Answers
I found out how to do it!
So for some reason if I put const data = { name: input.value } and put body: JSON.stringify(data) it works properly
Thanks to everyone who tried to help me
The error message:
Is telling you that the document field named
first
containsundefined
, which is invalid in Firestore. You will need to make sure that you pass a correct value when you calladdDoc
.We can’t debug this for you because we can’t see the value of
req.body.name
that you’re using here: