【问题标题】:Posting result of axiosaxios的发布结果
【发布时间】:2022-01-09 07:52:28
【问题描述】:

目前有这段代码它可以让我得到我需要的数据,但是我知道如何在网站页面而不是控制台文件上发布/展示数据?我尝试了帖子和我能想到的一切

const express = require('express');
const app = express();
app.listen(3000, () =>console.log('success'));
app.use(express.static('public'));


var axios = require('axios');
const { response } = require('express');

var config = {
 // method -> 'get', 'post', 'delete', 'put'
  method: 'get',
  // API endpoint -> 'https://api.eventyay.com/v1/event-locations'; 
  // API endpoint with query parameters -> 'https://api.eventyay.com/v1/event-locations?sort=name'
  url: 'https://api.eventyay.com/v1/event-locations',
  // sindle header -> header: { 'key': 'value'}
  // multiple header -> header: { 'key': 'value', 'key': 'value'}
  headers: { }
};

// If API response is success then would be executed, else catch block would be executed.
axios(config).then((response) => {
    // data = response.data
    // To parse data to json -> JSON.parse(response.data)
    // To parse data to string -> JSON.stringify(response.data)
  console.log(JSON.stringify(response.data))
  return response.data;
})
.catch((error) => {
  console.log(error)
});

【问题讨论】:

  • 听起来您想添加一个返回此数据的快速 API 路由?这样您就可以在您的网站上加载 /my-api-path 并取回 JSON?这种模式在网上有很好的记录。
  • 嗨,是的,我试过了,每次我不确定时它都会返回一个错误
  • 您的代码中没有任何快速路由。这个问题可能会被关闭,因为它没有足够的调试细节。请阅读how to ask 和how to create a minimal reproducible example,并编辑此问题,如果此问题已关闭,请打开一个新问题。如果“它”“返回错误”,我们无法在不知道其中任何一个含义的情况下为您提供帮助。
  • 我删除了它,因为它一直导致我。错误和或b只是屏幕上没有发生任何事情我是编码新手,我不介意问题是否被关闭我想如果它不在这里我可以在某个地方获得帮助然后idk但谢谢你的时间。跨度>

标签: javascript express axios


【解决方案1】:

试试这段代码,它会监听/my-api-path并返回结果。

const express = require('express')
const app = express()
const port = 3000
var axios = require('axios');

app.use(express.static('public'));

app.get('/my-api-path', (req, res) => {
  var config = {
 // method -> 'get', 'post', 'delete', 'put'
  method: 'get',
  // API endpoint -> 'https://api.eventyay.com/v1/event-locations'; 
  // API endpoint with query parameters -> 'https://api.eventyay.com/v1/event-locations?sort=name'
  url: 'https://api.eventyay.com/v1/event-locations',
  // sindle header -> header: { 'key': 'value'}
  // multiple header -> header: { 'key': 'value', 'key': 'value'}
  headers: { }
};

// If API response is success then would be executed, else catch block would be executed.
axios(config).then((response) => {
    // data = response.data
    // To parse data to json -> JSON.parse(response.data)
    // To parse data to string -> JSON.stringify(response.data)
  console.log(JSON.stringify(response.data))
  res.send(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error)
res.send("Error "+error.toString());
});
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 2022-12-10
    • 1970-01-01
    • 2020-11-09
    • 2018-06-01
    • 2018-07-18
    • 2020-11-28
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多