簡體   English   中英

通過節點和表達在React應用程序中打開URL

[英]Open URL in React application via node and express

我試圖通過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);

在這里,我發送url在UI上打開。

對於服務器我使用express-generator ,下面是路由器的代碼。 還設置了使用cors和header。

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();
  });

路線/ 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;

在route / openurl中,我在req.body中獲取了URL。 如何獲取給定的url響應並將其發送到客戶端以在UI上打開它?

這是正確的方法嗎? 因為我正在尋找可能的選擇。

您需要對用戶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);
  })


})

或者只是一種簡單的方法,您可以在您的反應應用程序中創建一個Iframe並顯示使用提供的URL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM