Noah Kanyo
Noah Kanyo

Reputation: 550

TypeError: Invalid URL

When i add a regular link with quotation marks to the function everything works, but when i am requesting the link from the front a type error appears.

I tried...

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

Looked through 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)
  }

The url preview should appear by sending the url entered into the input box to the backend. The url should make a roundtrip from front to backend rendering the image, description...

Upvotes: 3

Views: 32104

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

You are using Template literal the wrong way. Template literals ARE strings and when you want to use a variable you don't have to wrap it in quotes.

i.e, in your example google.com becomes 'google.com', Notice the extra quote.

it will be,

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

Upvotes: 2

Related Questions