【问题标题】:TypeError: Invalid URL类型错误:无效的 URL
【发布时间】:2019-07-04 11:21:51
【问题描述】:

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

我试过了……

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 预览。 url 应该从前端到后端进行往返渲染图像,描述......

【问题讨论】:

  • 使用模板字面量时不需要引号,它应该只是`${url1}`
  • 为什么首先使用模板文字?如果您能够使用if (url1 === '')检查 参数,那么grabity.grabIt(url1); 不应该已经做到了吗?真的很奇怪,如果该方法实际上需要额外的引号 in 值。
  • 非常感谢大家。

标签: javascript node.js


【解决方案1】:

您以错误的方式使用模板文字。模板文字是字符串,当你想使用一个变量时,你不必用引号括起来。

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

会的,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2017-09-05
    • 2013-01-25
    • 2016-05-20
    • 1970-01-01
    相关资源
    最近更新 更多