测试fastapi对Next.js的响应。

发布于 2025-01-26 19:19:58 字数 2327 浏览 2 评论 0 原文

当我查询本地开发人员的fastapi端点时,我的提取被困在等待中。

关注此博客和其他一些博客-g https://damaris-goebel.medium.com/ Promise-Pred-predend-60482132574d

使用此fetch代码(简化了它只是为了使简单的解决方案工作,它可以使一个简单的解决方案都可以

function fastapiRequest(path) {
    return fetch(`${path}`)
      .then((response) => {
        return response;
      }
      );

正常工作)ie,

const xxxx = fastapiRequest(
    `http://0.0.0.0:8008/xcascasc/Dexaa/Emo.json?Magic=Dexxaa&emotion=expressions`
  );

理想情况下,我想使用usewr来执行此操作,因为我使用sext.js,js,js,js,js,js,js,js,但首先,只需它才能工作:)

这样的邮递员查询正常工作,可以返回一个值

curl --location --request GET 'http://0.0.0.0:8008/xcaxc/dexxa/emo.json?analysis=statistical&substance=dexxa&emo=powa' \
--header 'x_token: 13wdxaxacxasdc1'

,在console.log中将值像这样,

data show here? Promise {<pending>}

而初始响应是

Response {type: 'cors', url: 'url', redirected: false, status: 200, ok: true, …}

根据答案进行更新的。

使用每个提出的答案,我仍然没有适当地返回数据。 IE,

function fastApiRequest(path) {
    console.log("really begins here");
    return fetch(`${path}`, { mode: 'cors' })
      .then((response) => {
        console.log('response', response);
        return response.json();
      })
      .catch((err) => {
        throw err;
      });
  }

async function test() {
    console.log('begins');

    return await fastApiRequest(
      `http://0.0.0.0:8008/xxxx/dex/adea.json?deaed=adedea&adee=deaed&adeada=adeeda`
    );
  }

  const ansa = test();

目前正在做出待处理的回应。

后端是由Fastapi构建的,在这些CORS上,我想知道我是否需要给它更多时间获取数据? (Postman正常工作:/)

def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

origins = [
    "http://moodmap.app",
    "http://localhost:3000/dashboard/MoodMap",
    "http://localhost:3000",
    "http://localhost",
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
        max_age=3600,

)

我在Docker容器中运行FastApi代码。

my fetch is stuck in pending when I query a fastapi endpoint in local dev.

followed this blog and a few others - https://damaris-goebel.medium.com/promise-pending-60482132574d

Using this fetch code (having simplified it drastically just to get a simple solution working)

function fastapiRequest(path) {
    return fetch(`${path}`)
      .then((response) => {
        return response;
      }
      );

into a constant variable i.e.,

const xxxx = fastapiRequest(
    `http://0.0.0.0:8008/xcascasc/Dexaa/Emo.json?Magic=Dexxaa&emotion=expressions`
  );

Ideally I want to use UseSWR to do this as I'm using next.js, but first of all, just need it to work :)

A postman query like this works fine to return a value

curl --location --request GET 'http://0.0.0.0:8008/xcaxc/dexxa/emo.json?analysis=statistical&substance=dexxa&emo=powa' \
--header 'x_token: 13wdxaxacxasdc1'

the value is left like this in console.log

data show here? Promise {<pending>}

With the initial response being

Response {type: 'cors', url: 'url', redirected: false, status: 200, ok: true, …}

Update based on answers.

Using each of the proposed answers, I am still not getting the data returned appropriately. i.e.,

function fastApiRequest(path) {
    console.log("really begins here");
    return fetch(`${path}`, { mode: 'cors' })
      .then((response) => {
        console.log('response', response);
        return response.json();
      })
      .catch((err) => {
        throw err;
      });
  }

async function test() {
    console.log('begins');

    return await fastApiRequest(
      `http://0.0.0.0:8008/xxxx/dex/adea.json?deaed=adedea&adee=deaed&adeada=adeeda`
    );
  }

  const ansa = test();

Is giving a response of pending at the moment.

The backend is built with fastapi, with these CORS, I'm wondering if I need to give it more time to get the data? (postman works fine :/)

def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

origins = [
    "http://moodmap.app",
    "http://localhost:3000/dashboard/MoodMap",
    "http://localhost:3000",
    "http://localhost",
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
        max_age=3600,

)

I am running the fastapi code in a docker container as well btw

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

随梦而飞# 2025-02-02 19:19:58

documentation

响应对象反过来不直接包含实际的JSON响应主体,而是整个HTTP响应的表示。因此,为了从响应对象中提取JSON主体内容,我们使用JSON()方法,该方法返回第二个诺言,该诺言以解析响应主体文本为JSON的结果。

.json()是一种异步方法(它返回承诺本身),因此您必须在下一个 .then()中分配分析值。因此,您的代码可以像这样更改。

function fastApiRequest(path) {
    let res;
    fetch(`${path}`)
    .then((response) => response.json())
    .then((data) => (res = data))
    .then(() => console.log(res));
    
    return res;
}

response =  fastApiRequest('https://proton.api.atomicassets.io/atomicassets/v1/accounts?limit=10');
console.log('response')

如果要使用 async/等待方法,则是代码。

async function fastApiRequest(path) {
  try {
    const response = await fetch(path);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

async function test() {
  console.log(await fastApiRequest('https://proton.api.atomicassets.io/atomicassets/v1/accounts?limit=10'))
}
test()

As per Documentation

The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.

.json() is an async method (it returns a Promise itself), so you have to assign the parsed value in the next .then(). So your code can be changed like this.

function fastApiRequest(path) {
    let res;
    fetch(`${path}`)
    .then((response) => response.json())
    .then((data) => (res = data))
    .then(() => console.log(res));
    
    return res;
}

response =  fastApiRequest('https://proton.api.atomicassets.io/atomicassets/v1/accounts?limit=10');
console.log('response')

If you want to use async/await approach, below is the code.

async function fastApiRequest(path) {
  try {
    const response = await fetch(path);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

async function test() {
  console.log(await fastApiRequest('https://proton.api.atomicassets.io/atomicassets/v1/accounts?limit=10'))
}
test()

当爱已成负担 2025-02-02 19:19:58

首先,如果是JSON API,则需要将响应解析为JSON。

function fastapiRequest(path) {
    return fetch(`${path}`)
      .then((response) => {
        return response.json();
       });
}

您需要为rsponse“等待”

您需要在


const xxxx = await fastapiRequest(
    `http://0.0.0.0:8008/xcascasc/Dexaa/Emo.json?Magic=Dexxaa&emotion=expressions`
  );

当您使用JavaScript中的fetch提出http请求时,它将返回a Promise ,它并没有卡住它只需要重新填充即可,您可以像上面的异步一样解决它,或者您可以使用。然后使用。 {/ *代码... */})函数,您还可以使用 .catch(()=&gt; {/ *处理错误... */})函数处理错误。

first you need to parse the response into json if it's a json API.

function fastapiRequest(path) {
    return fetch(`${path}`)
      .then((response) => {
        return response.json();
       });
}

you need to 'await' for the rsponse

you need to write the below code in an async function

const xxxx = await fastapiRequest(
    `http://0.0.0.0:8008/xcascasc/Dexaa/Emo.json?Magic=Dexxaa&emotion=expressions`
  );

When you make an http request using fetch in javascript it will return a Promise, it's not stuck it's just need to be resloved, you can resolve it just like the above code with async await, or you can use the .then(() => { /* code... */ }) function, you can also use .catch(() => { /* handle error... */ }) function to handle errors.

蓝梦月影 2025-02-02 19:19:58

curl 中,您使用 X_Token 作为标头变量,如果需要,您也需要使用路径传递标头。所有其他答案也有效。

In Your curl you use x_token as header variable, if it's required you need to pass a header with your path too. All other answers are valid too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文