首页 > 解决方案 > Express.js Find URL of client consuming REST API

问题描述

Lets say, I have a server running at: https://example.com The code in server:

const express = require("express");
const app = express();

app.get('/',(req, res)=>{
  let data = {'Hello':'World'}
  res.json(data);
});

app.post('/',(req, res)=>{
  let name = req.body.name;
  let email = req.body.email;
  res.json({name, email});
});

app.listen(3000);

Now, there is a client: https://website.com, trying to access server response by making a GET and POST request. (No API key is required)

How can the server find the web address of the client? In this example, I want the server (example.com) to determine the client's URL (website.com) and save it in the database. req.hostname() is not giving the desired output..

标签: node.jsrestexpress

解决方案


req.hostname是您要查找的内容。

更新:

重新阅读您的问题后,我认为您想要的是识别跨域请求,您将改为使用Origin标题。

var origin = req.get('origin');

请注意,一些跨域请求需要通过预检”请求进行验证:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});

推荐阅读