通过post将值从ajax传递到节点

时间:2018-11-07 00:04:52

标签: node.js express

我已经就此进行了回复,但无法弄清楚。我正在尝试将某些数据从文件传递到正在运行节点快速服务器的url。我之前对此没有任何知识,所以我确定我正在弄乱一些东西。

这是我的ajax调用:

appendChoiceList = (title: string, selected: string) => {
    console.log('selected:' + selected);
    console.log('new choice:' + title);
    const newOptionRequest: IWorkloadRequest = {
      optionTitle: title,
      selectedOption: selected
    };

    // tslint:disable-next-line:prefer-const
    for (let item of this.state.userChoices) {
      console.log(item);
      if (item.optionTitle === newOptionRequest.optionTitle) {
        // If user has already selected this before repalce it
        console.log(item);
        // tslint:disable-next-line:prefer-const
        let i = this.state.userChoices.indexOf(item);
        console.log(i);
        this.state.userChoices[i] = newOptionRequest;
      } else {
        // if this choice has not been set before
        this.state.userChoices.push(newOptionRequest);
      }
    }
  };

这是我的server.js文件,位于服务器上的node-webshot目录中。 我尝试过:

jQuery(document).ready(function($) {
  $("#preview_btn").click(function(event) {
      if($("#user_input").val() == ""){
         return false;
      }

    var tsid = "Hello there, you big bad server you...";

    $.ajax({
  type: 'POST',
  data: {str: tsid},
  url: 'https://myurl.com/preview/node-webshot/testing',
  success: function (data) {
    alert(data);
  }
}); 
});
});

这基于另一个答案:

var express = require('express');
var app = express();


app.post('/testing', function(req,res){
    let inputContent = req.body.textField;
    console.log(inputContent);
});

app.listen(8000);

当我单击调用ajax函数的预览按钮时,我得到

var express = require('express');
var bodyParser = require('body-parser')
var app = express();

app.use(bodyParser());

app.post('/testing', function(req, res) {
  var obj = {};
  console.log('body' + JSON.strigify(req.body));
  res.send(req.body);
});

app.listen(3000);

我还确保在服务器上启动了server.js文件。 任何帮助将不胜感激,谢谢!

0 个答案:

没有答案