简体   繁体   中英

access ajax request in nodejs server

I want to send an AST of parsed JS code to a server, where the server should process the AST and send back a list of completions. However when I log the AST to the console on the client right before sending it, it looks like this:

[ { "id":0, "type":"Program", "children":[1] }, { "id":1, "type":"FunctionDeclaration", "children":[2,3] }, { "id":2, "type":"Identifier", "value":"loonar" }, { "id":3, "type":"BlockStatement", "children":[4] }, { "id":4, "type":"ReturnStatement", "children":[5] }, { "id":5, "type":"LiteralNumber", "value":"101" }, 0]

On the server it looks like this:

{ '[ { "id":0, "type":"Program", "children":': [ { '2,3': [Array] } ] }

What do I do wrong?

client code:

function completion(cm_editor, ast) {
    var url = 'http://localhost:1337/ast'
    $.ajax({
        type: 'POST',
        data: JSON.stringify(ast),
        url: url,
        success: function(data) {
            // code ... 
        }
        error: function() {
            // code ...
        }

server code:

router.post('/ast', function(req, res) {
    console.log(req.body);
    // code ...
}

(I'm using express and bodyParser:)

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
const port = 1337;

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(router);
app.listen(port, function() { ... });

//router.post(...

You are sending the AST as a string data: JSON.stringify(ast) so your server will receive that as a string.

You can do two things here.

First one : parse the json in the server

console.log(JSON.parse(req.body));

Second one : Just send the json data without parse it in the client (I think this is the right one)

$.ajax({
    type: 'POST',
    data: ast, // just send your json here without stringify it
    url: url,
    success: function(data) {
        // code ... 
    }
    error: function() {
        // code ...
    }

UPDATE

This is the correct answer after some conversation in the comments

$.ajax({
    type: 'POST',
    data: { ast } , // just send your json here inside brackets
    url: url,
    success: function(data) {
        // code ... 
    }
    error: function() {
        // code ...
    }

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