【问题标题】:"TypeError: path.substring is not a function" Node,js when I try to read a json sent with POST“TypeError:path.substring 不是函数”节点,js 当我尝试读取用 POST 发送的 json 时
【发布时间】:2019-10-04 05:33:15
【问题描述】:

我正在使用 Node.Js 设置 Web 服务器,并且正在从 javascript 脚本发出登录 POST 请求(使用 JQuery 方法 %.post())。我不明白问题出在哪里,但我很确定服务器无法正确读取随数据发送的 JSON 文件,因为当我使用 JSON 文件的值时,它们是未定义的

我在我的 Windows 10 计算机上使用 Node.js 来回复 POST 和 GET 请求

服务器端:

var port = 8001;
const express = require('express');
const path = require('path');
const app = express();
const bodyParser = require('body-parser');

app.use('/', express.static('client'));
app.use(bodyParser.json());
app.post('/login',function(req,res){
    var username = req.body.email;
    var password = req.body.password;
        \\This returns "login successful undefined undefined"
    console.log('login successful ' + username + " " + password + "\n") ;
    var data = {
        email: username,
        password: password
    }
    res.sendFile(data);
})

客户端

function login(){
    var em = document.getElementById("emailForm").value;
    var psw = document.getElementById("passwordForm").value;

    var account = {
        "email": em,
        "password": psw
    }
    console.log(account.email + " : " + account.password);
    document.cookie = account;
    $.ajax({
        url: "http://localhost:8001/login",
        type: "POST",
        crossDomain: true,
        data: JSON.stringify(account),
        dataType: "json",
        success: function (response) {
            var resp = JSON.parse(response)
            alert(resp.status);
        },
        error: function (xhr, status) {
            alert("error:\nStatus: " + status + "\nXHR: " + xhr);
        }
    });
}

服务器端错误信息是:

TypeError: path.substring 不是函数 在exports.isAbsolute (C:\Users\39334\OneDrive\University\DA DARE\Programmazione web e mobile\Progetto\web-app\node_modules\express\lib\utils.js:59:23)

在 nodejs 终端上显示

【问题讨论】:

    标签: jquery node.js json ajax express


    【解决方案1】:

    您收到错误是因为您使用的是 res.sendFile,这需要您指定文件的绝对 URL。

    当您尝试使用 JSON 响应时,您可以改用它:

    res.json(data)
    

    此外,您需要将 contentType 添加到您的 $.ajax() 调用中,以告知服务器您正在发送 JSON:

    $.ajax({
      // ...
      contentType: "application/json",
      // ...
    }
    

    我希望这会有所帮助。

    【讨论】:

    • 这很完美!非常感谢。我想在客户端添加,在成功请求功能上,var resp = JSON.parse(response) 不是必需的。需要使用var resp = response
    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 2015-08-20
    • 2014-04-15
    • 2019-07-12
    • 1970-01-01
    • 2013-07-07
    • 2018-05-11
    • 1970-01-01
    相关资源
    最近更新 更多