我不知道你的IP,我可以调用你的接口吗,为什么?

880 阅读1分钟

憨憨问了一个问题:

前提条件是我们不知道B服务的IP,A服务部署页面服务,B服务提供某个接口,B访问A页面,能成功执行B服务接口吗?

答案是可以

那我们验证一下是否可以,准备一个虚拟机。

A服务浏览器打开A页面,为了方便测试我把B的接口放到登录按钮的点击事件,A服务调用B服务接口是失败的!

1719053665601.jpg A服务上的代码如下:


// html
<el-button @click="getRequest">登录</el-button>
// js
import axios from 'axios';
const getRequest = () => {
	let url = 'http://127.0.0.1:3000/api/hello'
    axios.get(url).then(response => {
          console.log('Response:', response);
    }).catch(error => {
          console.error('Error:');
    });
};

B服务浏览器打开A页面点击登录按钮,触发请求hello接口,请求成功!

1719054415889.jpg

B服务的代码如下:

const express = require('express');  
const app = express();  
const PORT = process.env.PORT || 3000;  
  
app.get('/api/hello', (req, res) => {  
  // 允许所有源访问
  res.header('Access-Control-Allow-Origin', '*');  
  // 发送响应  
  res.json({ message: 'Hello, World!' });  
});  
  
app.listen(PORT, () => {  
  console.log(`Server is running on port ${PORT}`);  
});

屏幕截图 2024-06-22 001149.png