【问题标题】:Having trouble understanding front-to-backend communication无法理解前端到后端的通信
【发布时间】:2020-09-13 15:52:18
【问题描述】:

我正在学习如何使用 Node 将前端连接到后端,但我无法理解。我有以下代码

后端.js

const express = require('express');
const cors = require('cors');


const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('<h1>hello, world.</h1>');
})

app.get('/testGet', (req, res) => {
  res.send('Golden rubbers in these denim pockets');
})

app.use(cors);

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

index.js

const axios = require('axios');

axios.get('http://localhost:8080/testGet').then(res => {
  console.log(res);
})

我难以理解的是为什么我必须在 GET 请求中指定端口和 localhost 作为主机名。我知道 express 服务器正在那个端口上运行,但是我看到人们在没有指定这些东西的情况下做同样的事情,例如:

axios.get('/testGet').then(res => {
  console.log(res);
})

我是否误解了教程中的某些内容?

【问题讨论】:

    标签: node.js express http request


    【解决方案1】:

    当您在未指定域的情况下执行 Ajax 请求时,浏览器将使用当前站点域。

    因此,如果您在浏览器中输入http://localhost:8080 并调用“/testGet”,请求将发送到http://localhost:8080/testGet。请注意,该端口是domain 的一部分(不同的端口是不同的域),如果未提供端口,则端口将默认为端口80

    您可以使用浏览器开发工具进行测试并查看网络流量。

    【讨论】:

    • 所以在生产环境中我必须在我的请求中指定端口,因为前端将在端口 80 上,所以我不能将端口 80 用于后端?例如,如果在我的前端有一个按钮,单击该按钮会向后端发出请求,该请求将发送到如下域:http://example.com:3000/testGet?
    • 在生产环境中,你的环境需要暴露在端口80上。您可以使用reverse proxy 来公开单个端口,但能够将请求路由到 Web 服务器或 API 服务器(请参阅:nginx.com/blog/deploying-nginx-plus-as-an-api-gateway-part-1
    猜你喜欢
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2011-09-12
    • 2013-03-02
    • 2019-10-22
    • 2020-08-15
    相关资源
    最近更新 更多