【问题标题】:JavaScript-ReactJS problem with GET fetch request ReactJS[已解决] GET fetch request ReactJS 的 JavaScript-ReactJS 问题
【发布时间】:2021-03-05 18:01:23
【问题描述】:

我正在尝试从 ReactJS 应用程序向 Node.js API 发出基本 GET 请求,但我收到状态为 304 的响应。我需要获得 200 状态才能将 GET 的响应保存在变量中。 (我在 3000 端口运行 Reactjs 应用,在 3300 端口运行 Nodejs API)

节点 API:

app.get('/serviciosextras', async (req, res) => {
let connection;
console.log(('Servicios Extras'));

try {
    connection = await oracledb.getConnection({
        user: 'portafolio',
        password: '123',
        connectString: "localhost:1521/orcl"
    });

    const result = await connection.execute(
        `SELECT  dep.id_departamento,
                 se.id_servicio,
                 se.precio_servicio            
         FROM departamento_servicio_detalle dsd
         JOIN departamento DEP ON (dsd.id_departamento = dep.id_departamento)
         JOIN servicio_extra SE ON (dsd.id_servicio = se.id_servicio)
         ORDER BY 1 ASC`
    )

    const resultSet = result.rows;

    let lista = [];

    resultSet.map(obj => {
        let serviciosSchema = {
            'id_departamento': obj[0],
            'id_servicio': obj[1],
            'precio_servicio': obj[2]
        }
        lista.push(serviciosSchema);
    });

    console.log(lista);

    res.json(lista);

    connection.close();
} catch (err) {
    console.error(err);
}
});

来自 Reactjs 的 GET 请求

const getExtraServices = () => {
let endpoint = `${URL}serviciosextras`;

const requestOptions = {
  method: "GET",
  mode: 'no-cors'
  // headers: {
  //   "Content-Type": "application/json",
  //   Accept: "application/json"
  // },
};
console.log(endpoint);

fetch(endpoint, requestOptions)
  .then((res, err) => {
    console.log(res);
  })
  .then(result => {
    console.log('fue aqui');
    console.log(result);
  })
  .catch(err => {
    console.log('ERROR');
    console.log(err);
  })
}

我从这个按钮调用方法:(onClick={getExtraServices()})

<Fab onClick={(e) => {
              e.preventDefault();
              getExtraServices();
            }} variant="extended">
              <NavigationIcon style={{marginRight: 'theme.spacing(1)'}} />
                Navigate
            </Fab>

所以...我得到了这个: Firefox Console when I clicked button to call getExtraServices() res 未定义

Network console of GET request 我收到了响应,但状态是 304,所以我无法从代码中获取此信息。 :/

Console of Nodejs API 这个console.log 如果来自console.log(lista) 之前发送res.json(lista)

有人知道我该如何解决这个问题吗?我需要获取 GET 请求的响应以在 ReactJS 应用程序中收取列表费用,但我不能,因为响应中有 body:null

解决方案:我知道为什么但是发送没有标头的请求并使用方法 :POST 问题已解决。

【问题讨论】:

  • console.log(endpoint) 返回正确的端点?
  • 在请求选项对象中有一个 POST,在后端它是 GET
  • @Versifiction 是的,我使用了正确的端点:/ 对不起,我已经编辑了它,我正在使用 post 进行测试,我忘记在这里更改它,使用 GET 是错误,抱歉

标签: javascript node.js reactjs get-request http-status-code-304


【解决方案1】:

错误 304 不是问题。

您似乎缺少将响应转换为 JSON 的语句。

这是一个来自 MDN 的示例:

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

特别是:

.then(response => response.json())

在您的代码中:

fetch(endpoint, requestOptions)
  .then((res, err) => {
    console.log(res); // logging res
    // no data being returned here
  })
  .then(result => {
    console.log('fue aqui');
    console.log(result); // therefore result is undefined
  })
  .catch(err => {
    console.log('ERROR');
    console.log(err);
  })

【讨论】:

  • 嗨@Will!哦,对不起,在我在这里复制的代码中,我在第一个“Then 语句”中忘记了 result.json:/ 但我尝试了这个并得到了“相同的结果”,不同之处在于请求状态为 200,但正文仍然为空(我认为它更改为状态 200,因为该方法是 post)
  • i.stack.imgur.com/ZhqWh.png (console.log(result) before result.json())
  • 看起来您有 2 个问题。 1)身体是空的。服务器不能发送您认为它正在发送的内容。 2) 结果还是undefined。我不知道您将 result.json() 放在哪里,但您的 then 方法中的箭头函数缺少返回语句。带有单个表达式的箭头函数将返回该结果。但是你在那里登录并添加了花括号。这些块需要为链中的下一步显式返回一些内容。
  • 我在这里上传了一个img imgur.com/a/X0vTSEV这是返回body:null。
  • 好的,这应该解决第二个问题。对于第一个问题,您可以在控制台中看到响应。服务器没有发送正文。如果你查看你的代码,你会发出一个数据库请求并得到一个响应(希望如此)。然后将lista 初始化为一个空数组。然后你映射你的数据库响应,但不存储映射的结果,所以它就被扔掉了。然后将空的lista 数组作为正文发送。你可能想要let lista = resultSet.map(obj =&gt; {... 或类似的东西。发送映射的结果集,而不是空数组。
猜你喜欢
  • 2019-02-13
  • 2019-12-29
  • 2020-11-21
  • 2020-09-08
  • 2021-03-02
  • 2021-03-18
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多