首页 > 解决方案 > JavaScript - 无法获取 /api/list

问题描述

我正在一个用户应该能够将项目发布到列表的网站上工作。现在,当我尝试发布某些内容时,会出现错误提示

Failed to load resource: the server responded with a status of 422 (Unprocessable Entity).

在控制台中单击它时,它会打开一个新的水龙头,它只是说

Cannot GET /api/list

同样在命令提示符下,它说

Unhandled rejection Error: Can't set headers after they are sent.

有谁知道为什么会这样以及我能做些什么来解决它?以下是我的一些代码片段:

索引.HTML:

fetch('/api/list', options)
    .then(response => response.json())
    .then(response => {
          if (response.status == 'OK') {
          console.log('song is added')
          getList(items)

          } else {
          alert(response.message)
        }
    })
 }

服务器.js:

app.post('/api/list', userIsAuthenticated, (req, res) => {
  let {
    titleArtist
    } = req.body

   let user_id = req.session.user.id

   // seaching for user id in database
   let query = {
     where: {
     userId: user_id
    }
  }

它也可能在代码中的其他地方出错。让我知道我是否应该发布更多代码片段。

标签: javascript

解决方案


This is because you are making a GET request to POST API.

This is how you can make POST request

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

推荐阅读