繁体   English   中英

如何从外部请求使本地服务器可用?

[英]How can I make my localhost server available from external requests?

我正在本地主机上的端口:3434上运行一个简单的nodejs服务器

const cors = require('cors');
const app = require('express')();
const bodyParser = require('body-parser')

app.use(bodyParser.json())
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(cors());

    app.get('/ping/:anystring', (req, res) => {
            console.log(req.params['anystring']);
            res.send({
                anystring: req.params['anystring']
            })
        });

    app.listen(3434);

我想从我的网站执行一些ajax调用。 我试图像这样配置路由器端口转发:

- name service: mylocalserver   
- porta ragnge: 3434    
- local ip: 192.168.1.19
- local port: 3434
- protocol: BOTH

但是当我这样做

fetch(publicIP:3434/ping/hello).then(res => {
  console.log(res);
})

我收到错误404

有人可以告诉我我在做什么错吗?

除非创建隧道,否则您将无法访问LAN之外的本地主机服务器。 我用ngrok

有一个用于ngrok的npm软件包 ,但是我无法正常工作,因此只要需要测试API时,我就从终端手动启动服务器。

另外,您还需要http

将此添加到您的app.js:

const http = require('http');

const newPort = //your port here (needs to be a different port than the port your app is currently using)

const server = http.createServer(function(req, res) {

  console.log(req); //code to handle requests to newPort
  res.end('Hello World);
});

app.listen(newPort, function() {
    console.log(`ngrok listening on ${newPort}`);
});

现在在终端中,安装ngrok之后 ,使用此ngrok http newPort ,其中newPort =您的端口

您可以通过转到localhost:4040查看发送到服务器的请求(这可能会因系统而异)

要将请求发送到您的本地主机,请执行以下操作:

- name service: mylocalserver //not sure
- porta ragnge: ???
- local ip: //ngrok gives you a url in terminal when you start the server (I'm not sure if you can reference an IP)
- local port: newPort
- protocol: http //(ngrok gives you a different url for http and https)

您可以使用本地隧道 ,它将本地主机上的端口映射到Web URL,而无需更改代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM