fetch post is giving me undefined for the posted data?
Asked Answered
D

1

1

Learning how to use Sapper. I have a component with form (the form has one field to enter an email address) and use fetch to post the data to the serverhandle. When I post the data and try to log the data I posted, it logs Undefined. I have no idea why and need help to figure it out.

Here is my component with the form and fetch post code:

<script>

  let emailvalue
  let url = "posthandle"


  async function handleSubmit(event) {
  console.log(event);
  console.log(event.target);

  emailvalue = event.target.email.value;

  console.log("this is from the variable--data--:" + content)

  // ******** Here is the Fetch() code
  fetch(url, {
  method: 'POST',
  body: JSON.stringify(emailvalue),
  headers: {
  'Content-Type': 'application/json'
  }
  })
  .then(r => {
  //this is gives the error that res stream is locked console.log(r.json())
  consolde.log(r)
  r.json()
  .then(function(result) {
  // this logs [object object]
  console.log("let us see" + result)
  })
  })
  .catch(err => {
  // POST error: do something...
  console.log('POST error', err.message)
  })    
  //post code example https://mcmap.net/q/1123191/-js-sapper-posting-data-to-server-the-right-way

  }

</script>


<p> {emailvalue} </p>

<form on:submit|preventDefault="{handleSubmit}">
  <label for="email">Email</label>
  <input required type="email" id="email" />
  <button type="submit">Create account</button>
</form>

The line that reads: console.log("let us see" + result) is showing [object Object] and I don't understand why?

My handle to manage the post :

     export async function post(req, res, next) {

        res.setHeader('Content-Type', 'application/json')
        /* Retrieve the data */
        var data = req.body;


        // Do something with the data...
        // it logs Undefined. Why?
        console.log("Here's the posted data:" + data );

        /* Returns the result */
        return res.end(JSON.stringify({ success: true }));

}

why data is undefined? Is the code wrong? Should I do something to read "data" and manage the actual data posted in the form?

Here is my server code (after @J) pointed out the body-parser issue:

import express from 'express';
import * as sapper from '@sapper/server';
const sirv = require('sirv');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const session = require('express-session');
const assets = sirv('static', {
    maxAge: 31536000, // 1Y
    immutable: true
});


app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
}))

app.use(assets, sapper.middleware()).listen(process.env.PORT, err => { if (err) console.log('error', err); });

If I console.log (r) from my fetch function which has the reponse. I get this in the console: Response {type: "basic", url: "http://localhost:3000/posthandle", redirected: false, status: 200, ok: true, …}

Docile answered 27/9, 2019 at 3:50 Comment(13)
Have you verified that emailvalue is not undefined?Mystagogue
is showing [object Object] and I don't understand why? because that's what object.toString() returns ... try console.log("let us see", result) and you'll see the resultHandset
@JaromandaX Thanks that worked, you're a life saver. I have been trying to figure this out all afternoon. Now to the server handle that received the data. The console.log is showing undefined? How do I access and get the value I enter in the form if my fetch code is correct, why the data variable is undefined? Any help is appreciated.Docile
@Mystagogue Yes, emailvalue is read and it shows the correct value I enter in the form and log that value correctly.Docile
do you have express body-parser module?Handset
@JaromandaX No. I don't. Do I need to install it and imported into the server.js?Docile
yes, that would probably fix your issueHandset
@JaromandaX Now we're getting somewhere. I installed the body-parser and configured it in the server.js ...now the data = body.req is showing an empty object {} and got an error when I entered console.log (r) in the fetch function. The error reads: VM695 form.eaa48bbd.js:135 Uncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream is lockedDocile
@JaromandaX Never mind. I got it to work. Thank you for you help. If you put your answer in a post, I will choose it as the correct answer so you get the credit for the answer. Have a great weekend.Docile
Did you get it to work with polka server instead of Express?Goodwife
@DanielRodríguezMeza No. I used expressjsDocile
@Docile I switched to Express but even though I get a 404 when trying to access the route and my structure is almost the same as yours.Goodwife
@DanielRodríguezMezado I can't help you without seeing your code. Start a question, post your code and write to me here with a link to your question and then I can take a look and try to help. Since I posted this question here I spent time with svelte and sapper and it works with expressjsDocile
G
0

I had to npm install body-parser --save and add it to the server.js. I had to add bodyParser.urlencoded and bodyParser.json to get it to work.

import sirv from 'sirv';
import polka from 'polka';
import compression from 'compression';
import * as sapper from '@sapper/server';

// const express = require('express')
const app = polka()
const bodyParser = require('body-parser')

const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app
  .use(
    compression({ threshold: 0 }),
    sirv('static', { dev }),
    sapper.middleware()
  )
  .listen(PORT, err => {
    if (err) console.log('error', err);
  });
Guano answered 17/7, 2020 at 1:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.