繁体   English   中英

我如何从 fetch 调用 EXpress NoseJs Javascript 中解析这个结果

[英]How can i parse this result from a fetch call EXpress NoseJs Javascript

这是我的脚本的代码,它在 index.html 文件中,我知道在那里是错误的,但首先我试图让它工作,然后我会移动它。

readOperaciones();
        
async function readOperaciones(){
            try{
                const listaOr = document.getElementById('listaOrdenada');

                const result = await fetch("http://localhost:8080/operaciones", {method: "GET"})
                const operaciones = await JSON.parse(result)
                //operaciones.forEach(t=>{


                    for (var i = 0; i < operaciones.length; i++) {
                    var row = operaciones[i];
                    console.log(row.codeemp);
}

                    /*tt = JSON.stringify(t);
                    const li = document.createElement("li");
                    li.textContent = tt.text;*/

                    /*t.forEach(cell=>{
                        const li = document.createElement("li")
                        li.textContent = cell.text;
                        li.id = cell.id;
                    })*/


                //})
            }
            catch(e){
                console.log("Error al leer las operaciones descriptas")
            }
        }

这是与快递的连接

const {Client} = require('pg');
const express = require ("express")

const app = express();
app.use(express.json())



const client = new Client({
  user: "postgres",
  password: "1234",
  host: "localhost",
  port: 5432,
  database: "webaduana",
})


app.get("/", (req, res) => res.sendFile(`${__dirname}/index.html`))

app.get("/operaciones", async (req, res) => {
    const rows = await readAll();
    res.setHeader("content-type", "application/json")
    res.send(JSON.stringify(rows))
})


async function readAll(){
    try{
        const results = await client.query("select * from operaciones")
        return results.rows;
    }
    catch(e){
        console.log(e)
        return [];
    }
}

我不知道是否需要提供更多信息,但我对所有这些代码的问题都在这里我尝试了很多方法,但我无法在 ol 元素中获得这些结果。 它没有给我任何错误,只是没有在 HTML 页面中打印任何内容

将 a.then 添加到 fetch 链并打印结果:

fetch('http://example.com/movies.json')
  .then(response => {
    console.log('response: ' + JSON.stringify(response));
  })
  ...
  ...

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

你可以使用 .json() 方法:

const fetched = await fetch("/url", {
  method: 'GET',
});

const fetchedJson: object = await fetched.json();

console.log(fetchedJson)

有几种方法可以做到这一点。

使用承诺

获取响应 object 固有地包含一些方法,可以帮助您在不同的 forms 中获得响应,例如 .json .json().text().status 点击此处了解详情。 因此,如果您只是想将答案解析为 JSON object,您可以这样做

function doSomethingOnParsedJson(res) {
  // Do something on the response here...
}

function readOperacions() {
  fetch("http://localhost:8080/operaciones", {
    method: "GET",
  })
     .then(res => res.json())
     .then(doSomethingOnParsedJson) // Pass in a function without parentheses
     .catch(console.error);
}

It's cleaner if you define a separate function which performs the job you want to do on the parsed response and pass the function (without parentheses) to then but you can also go ahead and give it a function directly like:

function readOperacions() {
  fetch("http://localhost:8080/operaciones", {
    method: "GET",
  })
     .then(res => res.json())
     .then(parsedResponse => {
       // do something...
     })
     .catch(console.error);
}

使用异步/等待

您还可以使用 async/await 功能来实现这一点。

function doSomethingOnParsedJson(res) {
  // Do something on the response here...
}

async function readOperacions() {
  try {
    // Get the response from the server.
    const res = await fetch("http://localhost:8080/operaciones", {
      method: "GET",
    });
  
    // Parse it into a JSON object.
    const parsedJson = res.json();

    // Do something on it.
    doSomethingOnParsedJson(parsedJson);
  } catch (error) {
    // Show an error if something unexpected happened.
  }
}

边注

有一种更简洁的方法可以在 Express 中发送 JSON 响应。 您可以在 Express 响应 object 上使用.json方法。

app.get("/operaciones", async (req, res) => {
  const rows = await readAll();

  /* Don't do this!
  res.setHeader("content-type", "application/json")
  res.send(JSON.stringify(rows))
  */

  /* Do this instead ;-) */
  res.json(rows);
})

瞧。 就是这么简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM