问题:在前端获取数据时无法打开端点。

huangapple go评论80阅读模式
英文:

Problems opening an endpoint for the front-end to fetch

问题

BACKEND CODE

app.get("/ranking", (req, res) => {
    res.render("ranking");
})

app.get("registros", () => {
    db.all("SELECT * FROM resultados", (err, rows) => {
        if (err) {
            console.error(err.message);
            return;
        }
        console.log(rows);
        return rows;
    });
})

FRONTEND CODE

function traerRegistrosDB() {
    fetch("/registros")
        .then(res => res.json())
        .then(res => res)
        .catch(() => {
            console.error("registros innacesibles")
        })
};

ERROR
http://localhost:3000/registros 404 (Not Found)

-I tried doing a console.log() in the back. It didn't show up

-Adding headers

-Going directly to the direction local..../registros

英文:

As said in the title, I'm writing a aplication in Node.Js and I need it to return a JSON (or at least console.log() the data, I can figure out the rest) I it seems like the URL doesn't exist

BACKEND CODE

app.get("/ranking",(req,res)=>{
    res.render("ranking");
})

app.get("registros",()=>{
    db.all("SELECT * FROM resultados", (err, rows) => {
        if (err) {
          console.error(err.message);
          return;
        }
        console.log(rows);
        return rows;
    });
})

FRONTEND CODE


function traerRegistrosDB(){

    fetch("/registros")
    .then(res=>res.json())
    .then(res => res)
    .catch(()=>{
        console.error("registros innacesibles")
    })
};

ERROR
http://localhost:3000/registros 404 (Not Found)

-I tried doing a console.log() in the back. It didn't show up

-Adding headers

-Going directly to the direction local..../registros

答案1

得分: 0

app.get("registros" 应该改为 app.get("/registros"

英文:

You miss a slash :
app.get("registros" should be app.get("/registros"

答案2

得分: 0

由于后端和前端地址不同,使用fetch时需要输入完整地址。

我分享以下示例。
假设后端地址为http://localhost:8080。

function traerRegistrosDB(){

    fetch("http://localhost:8080/registros")
    .then(res=>res.json())
    .then(res => res)
    .catch(()=>{
        console.error("registros innacesibles")
    })
};
英文:

Since the backend and frontend addresses are different, you need to enter the full address when using fetch.

I am sharing the example below.
Suppose the backend address is http://localhost:8080.

function traerRegistrosDB(){

    fetch("http://localhost:8080/registros")
    .then(res=>res.json())
    .then(res => res)
    .catch(()=>{
        console.error("registros innacesibles")
    })
};

huangapple
  • 本文由 发表于 2023年7月11日 06:40:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657742.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定