You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js本地站点提交表单时子路径无法访问 手动输入URL可正常打开

表单提交提示站点无法提供安全连接问题

问题描述

我在localhost:8080上部署了一个表单页面,输入表单数据(用户名和密码)后点击提交,预期会向localhost:8080/submit发送POST请求,跳转后页面显示"Submit page"文本。现在的问题是:我手动在浏览器地址栏输入"localhost:8080/submit"可以正常访问,但点击表单提交按钮时会提示“此站点无法提供安全连接”,访问失败。

相关代码

script.js

const url = "https://localhost:8080";
const data = {
    "user": "user",
    "pass": "pass"
}

function send() {
    alert("Sent")
    $.post(url, data, function (data, status) {
        console.log("Sent " + data + ", status is: " + status)
    });
}

styles.css

body {
    background-color: #444444;
}

.form-div {
    width: 100%;
    height: auto;
    text-align: center;
    justify-content: center;
    align-content: center;
    border: 1px solid red;
}

form {
    color: white;
}

页面HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Harley Swift</title>
    <link rel='stylesheet' href='styles.css'/>
    <script type="text/javascript" src="script.js"></script>
</head>

<body>
<div class="form-div">
    <form method="POST" action="https://localhost:8080/submit">
        <div>
            <label for="user">Username</label>
            <input name="user" type="text" id="user"><br>
        </div>

        <div>
            <label for="pass">Password</label>
            <input name="pass" type="password" id="pass"><br>
        </div>
        <br>
        <div>
            <button class="btn" onclick="send()">Submit</button>
        </div>
    </form>
</div>
</body>
</html>

问题原因与解决方案

核心原因

你本地启动的Node.js服务仅开启了HTTP协议,没有配置HTTPS相关的SSL证书,但是前端代码里所有请求地址都指定了https://协议,请求HTTPS端口时服务端没有对应的响应能力,就会触发安全连接报错。你手动在地址栏输入地址时,浏览器默认会用http://协议请求,所以可以正常访问。

修复步骤

  1. 修改表单的action属性,把https://localhost:8080/submit改为相对路径/submit即可,相对路径会自动匹配当前页面的协议、域名和端口,后续调整服务配置也不需要修改前端代码。
  2. 修正script.js中的配置:
    • 把url常量的协议改为http://,同时补全请求路径为/submit,原代码请求的是根路径没有匹配到提交接口
    • 你当前的提交按钮同时绑定了表单默认提交和异步AJAX提交两个行为,如果不需要异步提交可以直接去掉按钮的onclick="send()"属性,保留原生表单提交即可满足跳转显示结果的需求;如果需要异步提交,要在send函数末尾添加return false阻止表单默认跳转行为。
  3. 改完后重启Node服务,清空浏览器缓存再测试提交即可。

内容的提问来源于stack exchange,提问作者user12348779

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:54:06