【问题标题】:Open URL in React application via node and express通过节点在 React 应用程序中打开 URL 并表达
【发布时间】:2019-09-03 07:29:03
【问题描述】:

我正在尝试通过node.jsexpressreactjs 应用程序中打开用户提供的URL。

我正在使用material-uiaxios。请在下面找到 UI 代码。

实际上这是一个 UX 测试项目的 POC,其中给出了要测试的应用程序的 URL,并且该应用程序将在父(主)应用程序中打开以进行测试。

UrlForm.js

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import axios from 'axios';

const styles = theme => ({
  container: {
    display: 'flex',
    flexWrap: 'wrap',
  },
  textField: {
    marginLeft: theme.spacing.unit,
    marginRight: theme.spacing.unit,
  },
  dense: {
    marginTop: 16,
  },
  menu: {
    width: 200,
  },
  root: {
    ...theme.mixins.gutters(),
    paddingTop: theme.spacing.unit * 2,
    paddingBottom: theme.spacing.unit * 2,
  },
  button: {
    margin: theme.spacing.unit,
  },
});

class UrlForm extends React.Component {
  state = {
    url: ''
  };

  handleChange = name => event => {
    this.setState({
      [name]: event.target.value,
    });
  };

  sendData = () => {
    console.log(this.state.url);
    axios.post("http://localhost:3001/openurl", { url: this.state.url })
       .then(res => console.log('Data send'))
       .catch(err => console.log(err.data))
    }

  render() {
    const { classes } = this.props;

    return (
        <Paper className={classes.root} elevation={1}>
      <form className={classes.container} noValidate autoComplete="off">
        <TextField
          id="outlined-name"
          label="URL"
          className={classes.textField}
          value={this.state.url}
          onChange={this.handleChange('url')}
          margin="normal"
          variant="outlined"
        />

        <Button variant="outlined" color="primary" onClick={() => { this.sendData(); }} size="small" className={classes.button}>
            Open
        </Button>
    </form>
    </Paper>
    );
  }
}

UrlForm.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(UrlForm);

在这里,我正在发送要在 UI 上打开的 url。

对于我使用express-generator 的服务器,下面是路由器的代码。 还使用cors 并设置标题。

app.js

app.use((req, res, next) => {
    // Check if the origin is whitelisted in the env vars
    res.set({
      // standard CORS headers
      'Access-Control-Allow-Origin': 'http://localhost:3000',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization, Accept, Accept-Language',
      'Access-Control-Allow-Credentials': true,
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',

      // addresses security issues identified by automated pen testing
      'X-Frame-Options': 'DENY',
      'X-Content-Type-Options': 'nosniff',
      'X-XSS-Protection': 1,
    });
    next();
  });

routes/index.js

// routes/index.js

import express from 'express';
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/openurl', function(req, res, next) {
  console.log(req);
  console.log(res);
})

export default router;

在路由 /openurl 中,我在 req.body 中获取 URL。如何获取给定的 url 响应并将其发送到客户端以在 UI 上打开它?

这是正确的方法吗?因为我正在寻找可能的选择。

【问题讨论】:

  • “打开”是什么意思?你想在哪里打开它?在浏览器中,还是在您的节点服务器上?您想访问服务器上的 html 吗?
  • @Beaulne 添加了截图以供参考。并修改了描述。
  • 抱歉,Open 是什么意思?就像显示网站的url去做url的字符串http://www.theurl.com?
  • @Beaulne 是的,在应用程序中显示网站,该网站 url 将由用户提供。

标签: node.js reactjs express axios material-ui


【解决方案1】:

您需要对用户 URL 进行 get 调用以获取响应:

首先,安装axiosn

npm install axios

然后在您的节点应用程序上:

const axios = require('axios');

router.post('/openurl', function(req, res, next) {

let url = req.body.url ; 

axios.get(url)
  .then(function (response) {

  //do what's you want with response

    console.log(response.data);
    res.json({  content :  response.data});

  })
  .catch(function (error) {
    console.log(error);
  })


})

或者只是一种简单的方法,你可以在你的 react 应用中创建一个 iframe 并显示使用提供的 URL

【讨论】:

  • 感谢您的回答。是的 iFrame 是其中一个选项,但我试图避免它,因为下一步是在用户与打开的 url 交互时定期截取给定 url 的屏幕截图。
  • 如果你只想截图试试 node-webshot 是非常好的包:github.com/brenden/node-webshot
  • 是的,我看到了,并将在下一阶段使用它。在您给出的答案中,我需要将 response.data 发送给客户端并在 html 元素中显示,对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多