2

I used sapper in the past and used endpoints many times. So when I tried to give sveltekit a try, I didn't expect to run into errors posting to an endpoint. My setup is simple, I used the steps in the document from kit.svelte.dev to scaffold a skeleton project. In my index.svelte I added a form:

<form on:submit|preventDefault={submitit}>
    <p>
    <label>Name :
        <input type="text"  placeholder="name"   aria-label="name" required bind:value={name}>
    </label>
</p>
<p>
    <label>Password :
        <input type="password" placeholder="password"   aria-label="password" required  bind:value={password}>
    </label>
</p>
    <button type="submit">Submit</button>
</form>

Inside the src folder, added formdata.js for an end point and added this code:

export function post  (request) {
    let formfields = JSON.parse(request.body)
    
    console.log("login.js name :", formfields.name)
    console.log("login.js password", formfields.password)

    return {
        status : 200,
        headers: {        
            'content-type': 'application/json'
        },
        body : {
            message : "login form submitted the login credentials",
            name : formfields.name,
            password : formfields.password,

        }
    }

} //end post handle

Back in my index.svelte file, I added the submitit fn :

<script>
    let name
    let password

    async function submitit(){
        console.log("name is :", name)
        console.log("password is :", password)
       
        let res = await fetch( 'formdata' ,{
        method : "post",
        headers: {        
        'content-type': 'application/json'
        },
        body : JSON.stringify({
            name : "name",
            password : "password"
        })        
    })// fetch
    let results = res.json()
        return {
            status : results.code,
            body : results
        }

    } //submitit
</script>

When I enter anything in the form fields and hit submit, I get the following error log:

"To access the request body use the text/json/arrayBuffer/formData methods, e.g. `body = await request.json()`. See https://github.com/sveltejs/kit/pull/3384 for details
at Object.get (file:///D:/mycode/2022/sveltekit/kittest/skeleton/.svelte-kit/runtime/server/index.js:2244:10)
    at post (D:\mycode\2022\sveltekit\kittest\skeleton\src\routes\formdata.js:4:41)"

I added async to my endpoint, didn't help.

Clearly something is wrong with my endpoint or maybe something needs to be updated. The error is stating request body but not clear if it is my page -index.svelte- or my endpoint -formdata.js - so any help would be apprecaited.


Update: When I change my endpoint to

let results = await request.json()

I get this in my console:

request.json is not a function
TypeError: request.json is not a function
    at post (D:\mycode\2022\sveltekit\kittest\skeleton\src\routes\formdata.js:2:36)
    at render_endpoint (file:///D:/mycode/2022/sveltekit/kittest/skeleton/.svelte-kit/runtime/server/index.js:117:25)
    at async resolve (file:///D:/mycode/2022/sveltekit/kittest/skeleton/.svelte-kit/runtime/server/index.js:2299:10)
    at async respond (file:///D:/mycode/2022/sveltekit/kittest/skeleton/.svelte-kit/runtime/server/index.js:2264:20)
    at async file:///D:/mycode/2022/sveltekit/kittest/skeleton/node_modules/@sveltejs/kit/dist/chunks/index.js:238:24
Line must be greater than or equal to 1, got 0
TypeError: Line must be greater than or equal to 1, got 0
    at BasicSourceMapConsumer.SourceMapConsumer_findMapping [as _findMapping] (D:\mycode\2022\sveltekit\kittest\skeleton\node_modules\vite\dist\node\chunks\dep-f5552faa.js:58887:13)
    at BasicSourceMapConsumer.SourceMapConsumer_originalPositionFor [as originalPositionFor] (D:\mycode\2022\sveltekit\kittest\skeleton\node_modules\vite\dist\node\chunks\dep-f5552faa.js:58956:22)
    at D:\mycode\2022\sveltekit\kittest\skeleton\node_modules\vite\dist\node\chunks\dep-f5552faa.js:59897:34
    at String.replace (<anonymous>)
    at D:\mycode\2022\sveltekit\kittest\skeleton\node_modules\vite\dist\node\chunks\dep-f5552faa.js:59885:21
    at Array.map (<anonymous>)
    at ssrRewriteStacktrace (D:\mycode\2022\sveltekit\kittest\skeleton\node_modules\vite\dist\node\chunks\dep-f5552faa.js:59884:10)
    at Object.ssrFixStacktrace (D:\mycode\2022\sveltekit\kittest\skeleton\node_modules\vite\dist\node\chunks\dep-f5552faa.js:60382:36)
    at Object.get_stack (file:///D:/mycode/2022/sveltekit/kittest/skeleton/node_modules/@sveltejs/kit/dist/chunks/index.js:244:14)
    at render_response (file:///D:/mycode/2022/sveltekit/kittest/skeleton/.svelte-kit/runtime/server/index.js:1085:25)

I found this in docs but I have no idea what does it mean or how to implement it: You cannot directly require JSON files, since SvelteKit expects svelte.config.js to be an ES module. If you'd like to include your application's version number or other information from package.json in your application, you can load JSON like so:

Marco
  • 1,051
  • 19
  • 41

1 Answers1

2

The error is in the console, indicating it's at the server side.

The issue is that request.body isn't a thing like it would be in Node. The request/response items are actually coming from the Fetch API.

Try changing

let formfields = JSON.parse(request.body)

to

let formfields = await request.json()

Similarly, in the front-end res.json() returns a Promise.

Try awaiting it:

let results = await res.json();
kibibu
  • 6,115
  • 1
  • 35
  • 41
  • Thanks for trying to help. I tried it but didn't work. It seems there is an error from the vite processor. – Marco Feb 03 '22 at 22:59
  • @Marco it's the same problem, just at the server side. I've updated the answer. – kibibu Feb 03 '22 at 23:08
  • 1
    I added the error that I get when I await request.json()...it says that request.json is not a function. – Marco Feb 04 '22 at 07:03
  • Thank you for your help. I got it to work but I don't know how to extract form fields from the output as it is showing stream readable and I found pr from Rich about changing the request object. I'll create another question and send you the link. Thank you for help. Really appreciate it. – Marco Feb 04 '22 at 16:14
  • my new question: https://stackoverflow.com/questions/70990443/unable-to-access-request-body-from-the-endpoint-js-in-sveltekit-skeleton-project – Marco Feb 04 '22 at 17:26
  • worked for me! just make sure to use `{request}` – Kayaba_Attribution Mar 13 '22 at 23:38