【问题标题】:GET request from local server using live-server使用 live-server 从本地服务器获取请求
【发布时间】:2022-02-13 21:22:19
【问题描述】:

我正在尝试从本地服务器获取数据,这是我的服务器以及我如何处理 GET 请求:

const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());

app.listen(port, () => {
  console.log(`app running on port: ${port}...`);
});

const responseToClient = (req, res) => {
  res.status(200).json({
    status: 'success',
    body: 'Hello from the server!',
  });
};

app.get('/api', responseToClient);

当我运行我的服务器并使用 Postman 向这个地址发送 GET 请求:127.0.0.1:3000/api 时,它运行良好。

问题是我创建了一个 html 页面和一个 js 文件,并希望通过它从我的本地服务器获取数据。这是我对我的 js 文件的获取请求:

const url = '/api';

const fetchData = async () => {
  try {
    const response = await fetch(url);
    const body = await response.json();
    alert(body);
  } catch (error) {
    alert(error);
  }
};
fetchData();

我使用 live-server (extension) 运行我的 html 文件,该服务器默认在端口 5500 上运行,因此我的获取请求的地址将是 127.0.0.1:5500/api(而不是 127.0.0.1:3000/api ),所以它不存在,我收到一条错误消息。

我尝试更改服务器的端口并将其设置为 5500(与 live-server 相同)但它不起作用。

如何运行本地服务器并使用实时服务器和我的 html 文件向其发送请求?

【问题讨论】:

    标签: node.js express fetch liveserver npm-live-server


    【解决方案1】:

    通过使用解决:

     const url = 'http://localhost:3000/api';
    

    而不是ip地址和安装cors中间件。

    【讨论】:

      【解决方案2】:

      如果您不想将 HTML 和 JS 文件静态化到 Express 服务器上,请尝试以下操作:

      const url = '/api'; // bad
      const url = '127.0.0.1:3000/api'; // better
      

      【讨论】:

      • 我试过了,但它似乎增加了我当前的地址,因为我收到了这个错误:GET 127.0.0.1:5500/127.0.0.1:3000/api404 (Not Found)
      • 试试https://127.0.0.1:3000/api 可能吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2014-07-08
      • 2011-03-11
      相关资源
      最近更新 更多