skip to Main Content

I have an app I am trying to finish that has a form with data that should be sent to the back end so that it can be saved to mongo db. I am currently trying to get it to show to the back ends console to verify it is being sent properly, so far I am able to see the payload when I run in on a production server but I can’t get any info to store onto my database. My mongo db is trying to access the data but all it does is make the folder for the users file where the information is supposed to be stored but the folder itself is empty.

What am I doing wrong?

this is the server where I am trying to connect to

app.set('port', 8080);
// app.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || 8080);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressValidator());
app.use(cors());
require('./config/mongo');

app.post("/backend/endpoint/v6", v6, (req, res) => {
    let firstName = req.body.firstName;
   
    
    console.log(firstName);
    res.send(`
      Your firstName is: ${firstName}
  

    `);
  });

here is the front end


  const onFinish = async values => {
        values.phoneNumber = values.prefix + values.phoneNumber.match(/[0-9]+/g).join('');
        setLoading(true)
        values.birthDate = values.birthDate.format('MM/DD/YYYY')
        const {firstName = values;
        const data = new FormData();

        data.append("firstName", firstName);
       
        let response = await api.registerUser(data);

        if (response.status === 200) {
            const {data, token} = await response.json();

            let obj = {};
            obj.token = token;
            obj.firstName = data.firstName;
            dispatch(login(obj))
            setSaved(true)
            props.next()

            
        } else
        if (form) {
            form.addEventListener("submit", (e) => {
              e.preventDefault();
              const formData = new FormData(form);
              axios
                .post("backend/endpoint/v6", formData, {
                  headers: {
                    "Content-Type": "multipart/form-data",
                  },
                })
                .then((res) => {
                  console.log(res);
                })
                .catch((err) => {
                  console.log(err);
                });
            });
        }
        
         {

            let data = await response.json()

            message.error({
                content: (<AlertMessage title="Error" content={data.message} status="error"/>),
                className: 'custom-class custom_message_container',
                icon: (<></>),
                duration: 2
            });
        }
        setLoading(false)
    };

 

    const onFinishFailed = errorInfo => {
        console.log('Failed:', errorInfo);
    };

   
    return (
        <>
            <div className="steps_component">
                <div className="steps_content_heading ">
                    <div className="steps_content_heading1">
                        Personal Info
                    </div>
                    <div className="steps_content_heading2">
                        Please enter your information and register.
                    </div>
                </div>
                <div>
                    <Form action="backend/endpoint/v6" method="POST" encType="multipart/form-date"
                    
                       
                        form={form}
                        name="basic"
                        initialValues={{remember: true, prefix: '+1'}}
                        onFinish={onFinish}

                        onFinishFailed={onFinishFailed}
                    >
                        <Row gutter={[16, 16]} style={{marginBottom: 0}}>
                            <Col span={12} style={{margin: 0}}>
                                <div className="form_label">First Name</div>
                                <Form.Item
                                    style={{marginBottom: 0}}
                                    name="firstName"
                                    rules={[
                                        {pattern: new RegExp(/^[a-zA-Z+']+$/),message: "Only Letters may be entered into the first name field"},

                                        {required: true, message: 'Please enter first name'}]}
                                >
                                    <Input placeholder="First Name"/>
                                </Form.Item>

I am currently running into this error when I try to register a user "Failed to execute ‘json’ on ‘Response’: body stream already read
TypeError: Failed to execute ‘json’ on ‘Response’: body stream already read
at onFinish (http://localhost:3000/static/js/bundle.js:5392:33) it is comming from this line " let data = await response.json()
" so I think this means that the info is being sent to the back ends console more than once but can’t be read? What am I doing wrong here, how can I fix it? any help is welcome.

2

Answers


  1. Chosen as BEST ANSWER

    I was able to resolve the issue by fetching the data to a new route on the server


  2. Just by the error, I think you called response.json() twice (in your frontend) which isn’t allowed. Use a variable to store the result to use it multiple times

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search