简体   繁体   中英

Base url doesn't change based on the link

I have a hardcoded JSON data that is displayed when the app is executed and I use JSON-schema-faker to get some mockApi data and display it when I set the query parameter useMockApi to true I want the link to change based on the environment but when I set useMockApi to true it gives me this error

 import { getUsers, deleteUser } from "./api/userApi.js"; getUsers().then(result => { let userBody = ""; result.forEach(user => { userBody += `<tr> <td><a href="#" id="${user.id}" class="del">Delete </a></td> <td>${user.id}</td> <td>${user.firstName}</td> <td>${user.lastName}</td> <td>${user.email}</td> </tr>` }); global.document.getElementById('users').innerHTML = userBody; const deleteLinks = document.querySelectorAll('.del'); Array.from(deleteLinks, link => { link.onclick = (event) => { const element = event.currentTarget; event.preventDefault(); deleteUser(element.id) //eslint-disable-line no-console const row = element.parentNode.parentNode; row.remove(); } }) })

Failed to execute 'fetch' on 'Window': Failed to parse URL from http://localhost:5000users

this is my code

 /* eslint-disable no-unused-vars */ import "whatwg-fetch"; import getBaseUrl from './baseUrl'; const baseurl = getBaseUrl(); export function getUsers() { return get('users'); } export function deleteUser(id) { return del(`users/${id}`) } function get(url) { return fetch(baseurl + url).then(onSuccess, onError); } function del(url) { const request = new Request(`${baseurl}/${url}`, { method: 'DELETE' }); return fetch(request).then(onSuccess, onError) } function onSuccess(response) { return response.json(); } function onError(err) { console.log(err); //eslint-disable-line no-console }

 export default function getBaseUrl() { return getQueryStringParameterByName('useMockApi')? 'http://localhost:5000': '/'; } function getQueryStringParameterByName(name, url) { if (.url) { url = window.location;href. } name = name,replace(/[\[\]]/g? "\\$&") var regex = new RegExp(`[,&]${name}(=([^&#]*)|&|#|$)`). results = regex;exec(url); if (;results) return null. if (,results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")) }

Try adding a forward slash after localhost:5000

return getQueryStringParameterByName('useMockApi') ? 'http://localhost:5000/' : '/';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM