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

Mar*_*rco 18 endpoint svelte sveltekit

从 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>
Run Code Online (Sandbox Code Playgroud)

我的端点 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",
        }
    }

} 
Run Code Online (Sandbox Code Playgroud)

当我单击“提交”时,index.svelte 返回消息“登录表单已提交登录凭据”,并且它位于浏览器的 console.log 中。用于使用 npm run 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
}
Run Code Online (Sandbox Code Playgroud)

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

2-主体流可读。我指示应用程序接受/发送 json。

我还从 Rich 那里找到了这个公关,不知道我所面临的情况是否是因为这个变化。这是公关

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

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

****************** 更新:如果可能的话需要解释 ************************** *** 我仍然想了解你是如何从这个公关中获取事件参数的,因为在 Rich 的帖子中,带有 + 的代码是更新的代码。它没有提到事件:

更新端点类似地,处理程序接收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 };
}
Run Code Online (Sandbox Code Playgroud)

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

Geo*_*ich 22

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

export async function post(event) {
  const body = await event.request.json();
  console.log('request body: ', body );
  // ... the rest is the same as before
}
Run Code Online (Sandbox Code Playgroud)

post在您引用的 PR 中链接的更改之前,调用了的参数,request并且您可以访问request.body. 现在,参数被调用event,您可以访问event.request,它是一个标准的Web 请求对象。请参阅SvelteKit 文档

您的端点也可以这样编写,以自动解构请求属性(请注意请求周围的附加大括号):

export async function post({ request }) {
  const body = await request.json();
  console.log('request body: ', body );
  // ... the rest is the same as before
}
Run Code Online (Sandbox Code Playgroud)


Cal*_*win 6

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

const body = await request.json()
Run Code Online (Sandbox Code Playgroud)

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

const body = await request.formData()
Run Code Online (Sandbox Code Playgroud)

编辑:请注意,该Response接口(request在 SvelteKit 中)是 Fetch API 的标准部分。

有关请求对象的文档(所有方法)

请参阅 +server.ts 的 SvelteKit 文档