简体   繁体   English

Node.js Express.js 发送 Jquery Ajax 帖子引发持续错误 - 我卡住了

[英]Node.js Express.js Send Jquery Ajax Post throws Constant Error - I'm stuck

I'm trying to make a very simple return coming from Node.js to Ajax.我正在尝试从 Node.js 到 Ajax 进行非常简单的返回。 I'm using Express.js to make this possible.我正在使用 Express.js 来实现这一点。

I have code from the previous route that I did in order to write and manage JSON files and it works just fine.为了编写和管理 JSON 文件,我有上一条路线的代码,它工作得很好。

The problem comes from the second route that always throws an error when I'm trying to make it return something with the JQuery ajax success method.问题来自第二条路线,当我尝试使用 JQuery ajax 成功方法返回某些内容时,它总是抛出错误。 It is the most simple form of send that I found but still doesn't work.这是我发现的最简单的发送形式,但仍然不起作用。

index.html索引.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test 2</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body>
    Cod: <input type="text" name="cod" id="cod">
    Text: <input type="text" name="text" id="text">
    <button id="boton">PRUEBA</button>
    <button id="getText">GET TEXT</button>
    
    <script>
        $('#boton').click(function() {
            let cod=$('#cod').val();
            let text=$('#text').val();
            console.log(cod);
            console.log(text);
            $.ajax({
                type: 'POST',
                data: {
                    cod: cod,
                    text: text,
                },
                url: 'http://localhost:1337/prueba'
            });
        });
        $('#getText').click(function() {
            $.ajax({
                type: 'POST',
                data: {

                },
                success: (result) => {
                    console.log(result);
                },
                error: (result) => {
                    console.log('ERROR');
                },
                url: 'http://localhost:1337/getText'
            });
        });
    </script>
</body>
</html>

app.js应用程序.js

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/prueba', function(req, res) {
    // ... First Route. The code here works just fine so I don't add it here.
});

app.post('/getText', function(req, res) {
    let text = "Hola mundo";
    console.log(text);

    res.send(text);
});

app.listen(1337, () => console.log('Started server at http://localhost:1337!'));

When you click the 'GET TEXT' Button it enters inside the '/getText' route in app.js and console.logs the text on the node.js terminal so that's not the issue.当您单击“获取文本”按钮时,它会进入 app.js 中的“/getText”路径内,并且控制台会在 node.js 终端上记录文本,所以这不是问题。

The issue seems to come from the res.send() function.问题似乎来自 res.send() function。

In the browser console it logs 'ERROR' as it appears in the ajax error method associated to the 'GET TEXT' Button.在浏览器控制台中,它会记录“错误”,因为它出现在与“获取文本”按钮关联的 ajax 错误方法中。 I can't find a way to make it return success.我找不到让它返回成功的方法。

Could anyone help me?有人可以帮我吗? I'm so stuck with this project for work.我非常坚持这个项目的工作。

looks like a CORS issue... do you serve index.html from the same location?看起来像CORS问题...您是否从同一位置提供 index.html?

It works serving index.html from node它可以从节点服务 index.html

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/prueba', function(req, res) {
    // ... First Route. The code here works just fine so I don't add it here.
});

app.post('/getText', function(req, res) {
    let text = "Hola mundo";
    console.log(text);

    res.send(text);
});

app.get('*', function (req, res) {   
    res.sendFile('index.html', {root: '.'})
   })

app.listen(1337, () => console.log('Started server at http://localhost:1337!'));

There are several options for node/express, eg express middleware node/express 有几个选项,例如express 中间件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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