无法从 sveltekit 骨架项目中的 endpoint.js 访问 request.body

Unable to access request.body from the endpoint.js in sveltekit skeleton project

从 sveltekit 应用启动骨架项目后。我的索引有一个形式:

<script>
    let name
    let password

    async function submitit(){
       // console.log("name is :", name)
       // console.log("password is :", password)
       
     const doit = async () =>{
        let res = await fetch( 'formdata' ,{
        method : "post",
        headers: {        
        'Accept': 'application/json',
        'content-type' : 'text/html; charset=UTF-8',
        //'Content-Type': 'multipart/form-data'
        },
        body : JSON.stringify({
            name : "name",
            password : "password"
        })        
    })// fetch
    let results =await res.json()
    console.log( "xxxxxxxxxxxxxxxxxxxxx"    , results )
    return results
    }       

     doit().then(data =>{
         console.log("data log : " , data)
     })


    } //submitit


</script>









<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>

我的端点formdata.js

export async function post(request) {    

    console.log("formdata js log of request : ", request)
    
    return {
        
        status : 200,
        headers: {        
            'content-type': 'application/json'
        },
        body : {            
            message : "login form submitted the login credentials",
        }
    }

} 

当我点击提交时,index.svelte returns 消息“登录表单提交了登录凭据”并且它在浏览器的 console.log 中。用于 运行 使用 npm 运行 dev 的应用程序的 cmd,记录 dataform.js 请求并打印以下内容:

formdata js log of request :  {
  request: Request {
    size: 0,
    follow: 20,
    compress: true,
    counter: 0,
    agent: undefined,
    highWaterMark: 16384,
    insecureHTTPParser: false,
    [Symbol(Body internals)]: {
      body: <Buffer 7b 22 6e 61 6d 65 22 3a 22 6e 61 6d 65 22 2c 22 70 61 73 73 77 6f 72 64 22 3a 22 70 61 73 73 77 6f 72 64 22 7d>,
      stream: [Readable],
      boundary: null,
      disturbed: false,
      error: null
    },
    [Symbol(Request internals)]: {
      method: 'POST',
      redirect: 'follow',
      headers: [Object],
      parsedURL: [URL],
      signal: null,
      referrer: undefined,
      referrerPolicy: ''
    }
  },
  url: URL {
    href: 'http://127.0.0.1:3000/formdata',
    origin: 'http://127.0.0.1:3000',
    protocol: 'http:',
    username: '',
    password: '',
    host: '127.0.0.1:3000',
    hostname: '127.0.0.1',
    port: '3000',
    pathname: '/formdata',
    search: '',
    searchParams: URLSearchParams {},
    hash: ''
  },
  params: {},
  locals: {},
  platform: undefined
}

注意以下几点: 1- 我的表单或 index.svelte 中的正文 json.stringify 中没有用户名或密码字段,但它在 url 部分下的请求日志中(尽管有虚拟文本,但它们都是空的我输入了 index.svelte)

2- 正文流是可读的。我向 accept/send json 表明了申请。

我也从 Rich 那里找到了这个 pr,不知道我现在面临的是不是因为这个变化。 Here is the PR

我对这个 sveltekit 迷路了。我对 Sapper 有很好的经验,我希望我能弄清楚 sveltekit,这样我就可以继续并开始开发我的应用程序,但这是任何应用程序处理表单数据的第一步。

============================================= ====================

****************** 更新:如果可能需要解释 ********************* ********* 我仍然想了解您是如何从这个 pr 中获得事件参数的,因为在 Rich 的 post 中,带有 + 的代码是更新后的代码。它没有提到事件:

正在更新端点 同样,处理程序接收 RequestEvent。大多数 GET 处理程序将保持不变,但任何需要读取请求正文的处理程序都需要更新:

-export async function post({ params, body }) {
+export async function post({ params, request }) {
+ const body = await request.formData(); // or request.json(), etc
  await do_something_with(params, body);
  return { status: 201 };
}

任何地方都没有提到活动。您如何获得关键字“event”作为函数的参数?

你说得对,PR 改变了你访问正文的方式。现在要访问端点中的请求正文,您必须使用:

const body = await request.json()

如果您直接使用表单发送数据(使用 action="/path/to/endpoint"),您将使用:

const body = await request.formData()

See SvelteKit docs for body parsing

您的端点现在应该如下所示:

export async function post(event) {
    const data = await event.request.json();
    console.log('formdata js log of request : ', data);

    // ... the rest is the same as before
}

在您引用的 PR 中链接的更改之前,post 的参数被称为 request,您可以访问 request.body。现在,该参数称为 event,您可以访问 event.request,这是一个标准的 web request object. See the SvelteKit docs

你的端点也可以这样写来自动解构请求属性(注意请求周围的额外大括号):

export async function post({ request }) {
    const data = await request.json();
    console.log('formdata js log of request : ', data);

    // ... the rest is the same as before
}