Я пытаюсь открыть предоставленный пользователем URL в приложении reactjs
через node.js
и express
.
Я использую material-ui
и axios
.Ниже приведен код для пользовательского интерфейса.
На самом деле это POC для проекта UX-тестирования, в котором указан URL-адрес приложения для тестирования, и это приложение будет открыто в родительском (основном) приложении для тестирования.
![enter image description here](https://i.stack.imgur.com/PXbSX.png)
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 для открытияна пользовательском интерфейсе.
Для сервера я использую 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();
});
routs / 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 я получаю URL в req.body.Как мне получить данный URL-ответ и отправить его клиенту, чтобы открыть его в пользовательском интерфейсе?
Это правильный путь или нет?Как я ищу возможные варианты.