Angular本地开发跳转外部URL异常:如何解决localhost拼接问题?
解决Angular项目中跳转外部URL时的路径拼接错误问题
嘿,我碰到过好多次这个问题了!你遇到的这个情况其实是因为浏览器把没有协议头(http/https)的URL当成了相对路径来处理,所以才会把www.example.com拼到当前的localhost:4200后面,形成了错误的localhost:4200/www.example.com地址。
下面给你几个简单有效的解决方法:
方法1:给URL加上完整的协议头
直接在URL开头加上https://(更推荐用HTTPS),这样浏览器就会明确识别这是一个外部的绝对URL,不会当成相对路径拼接:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-main', templateUrl: './main.component.html' }) export class MainComponent implements OnInit { public title: string; constructor(){} ngOnInit(){ // 加上完整的HTTPS协议头 window.location.href = 'https://www.example.com'; } }
方法2:使用协议相对URL
如果你不确定目标网站用的是http还是https,或者想让URL自动继承当前页面的协议(比如当前是http就用http,当前是https就用https),可以用双斜杠开头的协议相对URL:
window.location.href = '//www.example.com';
这种写法会自动适配当前页面的协议,兼容性也很好。
小提示
如果你的URL是动态生成的(比如从后端接口获取),记得提前检查是否包含协议头。如果没有的话,可以通过代码自动补充,比如:
const targetUrl = 'www.example.com'; // 检查是否包含协议头,没有则添加https:// const fullUrl = targetUrl.startsWith('http') ? targetUrl : `https://${targetUrl}`; window.location.href = fullUrl;
另外要注意:Angular的Router模块是用来处理内部路由跳转的,比如跳转到项目里的其他组件页面,不要用它来跳外部URL,外部跳转还是用原生的window.location.href或者location.assign()更靠谱~
内容的提问来源于stack exchange,提问作者sonEtLumiere
相关产品推荐
相关产品推荐

