简体   繁体   English

使用express在nodejs中获取两个错误

[英]Getting two error's in nodejs using express

(I know this has a bad title) (我知道这个标题不好)
I'm using firebase and express for this project but this doesn't work.我正在使用 firebase 并为这个项目表示,但这不起作用。

src/index.js 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) (firebase 配置中的所有内容实际上都在我的真实 js 文件中)

src/views/index.ejs 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.添加文档时出错:[FirebaseError: Function addDoc() 使用无效数据调用。 Unsupported field value: undefined (found in field first in document users/VI9jpmKrASca4PhrTxYC)] { code: 'invalid-argument', customData: undefined, toString: [Function (anonymous)] }不支持的字段值:未定义(在文档 users/VI9jpmKrASca4PhrTxYC 中的字段第一个中找到)] { code: 'invalid-argument', customData: undefined, toString: [Function (anonymous)] }

and in my console(firefox) Im getting this在我的控制台(firefox)中我得到了这个

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data未捕获(承诺中)语法错误:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符

also if I use insomnia or rest clinet and pass in an object like { "name":"hello", } it works properly另外,如果我使用失眠症或 rest clinet 并传入 object 像 { "name":"hello", } 它可以正常工作

The error message:错误信息:

Unsupported field value: undefined (found in field first in document users/VI9jpmKrASca4PhrTxYC)]不支持的字段值:未定义(在文档 users/VI9jpmKrASca4PhrTxYC 中的字段第一个中找到)]

Is telling you that the document field named first contains undefined , which is invalid in Firestore.告诉您名为first的文档字段包含undefined ,这在 Firestore 中无效。 You will need to make sure that you pass a correct value when you call addDoc .您需要确保在调用addDoc时传递了正确的值。

We can't debug this for you because we can't see the value of req.body.name that you're using here:我们无法为您调试,因为我们无法看到您在此处使用的req.body.name的值:

add(req.body.name);

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因此,由于某种原因,如果我输入 const data = { name: input.value } 并输入 body: JSON.stringify(data) 它可以正常工作

Thanks to everyone who tried to help me感谢所有试图帮助我的人

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 firebase 上部署 react 前端和 express/nodejs 后端 - Deploying react frontend & express/nodejs backend on firebase 使用 NodeJS 将多个文件上传到 AWS S3 - Uploading multiple files to AWS S3 using NodeJS 使用 nodejs 从 AWS S3 存储桶下载图像文件,更新:12/12 - downloading image file from AWS S3 bucket using nodejs, UPDATE :12/12 Firebase 托管 NodeJS Express 应用程序不工作,超时很多 - Firebase Hosting NodeJS Express App not working, times out a lot 尝试在前端显示图像(使用 react native、nodejs 和 amazon s3) - Attempting to display image on front end (using react native, nodejs and amazon s3) 错误:invalid_grant,用于使用刷新令牌获取访问令牌 - error: invalid_grant , for getting access token using refresh token 如何在部署在 EC2 实例上的 Nodejs Express 服务器中使用 HTTPS? - How to use HTTPS in Nodejs express server Deployed on EC2 instance? 我收到多个错误:尝试在 aws s3 存储桶中上传文件时出现意外字段 - I am getting multer error : unexpected field when i was trying to upload files in aws s3 bucket 使用 firebase 和 react native 出现异常错误 - Getting an unusual error using firebase with react native 当我向我显示此错误“无法读取未定义的属性(读取'_internalPath')”时,我尝试使用nodejs和firestore中的过滤器获取数据 - I tried to get data using filter in nodejs and firestore when show me this error "Cannot read properties of undefined (reading '_internalPath')"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM