TypeError:无效的URL

时间:2019-07-04 11:21:51

标签: javascript node.js

当我在函数中添加带引号的常规链接时,一切正常,但是当我从前端请求链接时,出现类型错误。

我尝试过...

JSON.stringify
const baseURL = new URL(url1)
const newURL = baseURL.href

浏览https://nodejs.org/api/url.html

//backend

const express = require('express');
const router = express.Router();
const grabity = require("grabity");
const { URL } = require('url');

router.post('/', sharedHandler);
router.get('/', sharedHandler);

async function sharedHandler(req, res, next) {
  if (req.body === ''){
    console.error('No Body found')
  } 

  const url1 = await req.body.value;
  console.log(req.body);
  if (url1 === ''){
    return;
  } else {
    try{
    let it = await grabity.grabIt(`'${url1}'`);
    // when regular link e.g "https://stackoverflow.com/" it works fine when i use template literals like above it gives me url typeError 
    console.log(it)
    res.json(it)
    }
    catch(err){
      console.log(err)
    }
  }
}

module.exports = router;
// front end
import React, {Component} from 'react';
import './App.css';
import MicrolinkCard from '@microlink/react';


class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      practiceText: "",
      description: "",
      value: "",
      image: ""
    };
  }

  grabityAPI() {
    fetch("http://localhost:9000/grabityLink")
        .then(res =>  res.json())
        .then(res => this.setState({ title: res.title, image: res.image, desc: res.description, favi: res.favicon }))
  }

  callAPI() {
    fetch("http://localhost:9000/testAPI")
        .then(res => res.json())
        .then(res => this.setState({ practiceText: res }));
  }

  componentWillMount() {
    this.callAPI();
    this.grabityAPI();
  }

  handleChange = async (e) => {
    e.preventDefault();
    this.setState({value: this.refs.value.value})
    const data = { value: this.state.value}

    const options = {
      method: 'POST',
      headers: { "Content-Type": "application/json; charset=utf-8" },
      body: 
        JSON.stringify(data),
    };

    await fetch("http://localhost:9000/grabityLink", options)
  }

URL预览应该通过将输入框中输入的URL发送到后端来显示。 网址应从前端到后端进行一次往返,以渲染图像,说明...

1 个答案:

答案 0 :(得分:0)

您使用模板文字的方式错误。模板文字是字符串,当您要使用变量时,不必将其用引号引起来。

即,在您的示例中,google.com变为'google.com',请注意多余的引号。

它将是

let it = await grabity.grabIt(`${url1}`); 
//or 
let it = await grabity.grabIt(url1)