2017-02-01 4 views
0

XMLhttprequest経由でノードにデータを送信しようとしています。データは次のようになります(/q/zmw:95632.1.99999.json)。 Nodeへの私の接続は正しいですが、空のオブジェクトを取得していたので、ヘッダーをContent-Type application/jsonに設定してデータを文字列化しました。しかし、Nodeは私に "予期しないトークン"を返します。私はそれが文字列のためだと推測しますが、データを文字列化しないと、データの "/"のためにエラーが発生します。純粋なJavascriptを使用しています。私はバニラのjavascriptでもっと堪能になりたいので、Axiosとjqueryから離れていきたいです。私は、URLの接頭辞と接尾辞を組み立てることによって、ノード内のAPIへの最終呼び出しを行います。XMLhttprequest経由の投稿をバニラのjavascriptの自分のノードサーバーにどのように送っていますか?

ここに私ですコード:

function getCityForecast(e){ 

    //User selects option data from an early JSONP request. 
    var id = document.getElementById('cities'); 
    var getValue = id.options[id.selectedIndex].value; 

    //Assembles the suffix for http request that I will do in Node. 
    var suffix = getValue + ".json"; 
    var string = JSON.stringify(suffix); 

    console.log(suffix); 

    var xhr = new XMLHttpRequest(); 

    xhr.open("POST", "http://localhost:3000/", true); 
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 
    xhr.send(string); 
} 

のNode.jsコード:

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

// ****************** Middle Ware ******************* 
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(bodyParser.json()); 

app.use(express.static(__dirname + '/public')); 

app.post('/', function(req, res){ 
    console.log('working'); 

    console.log(req.body); 
}); 

app.listen(3000, function() { console.log('listening')}); 
+0

POSTリクエストのデータを適切な形式にするための 'FormData'オブジェクトを参照してください:https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objectsまたは' XMLHttpRequest'以外のものを使用するこれを参照してください:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files – jfriend00

+0

これはファイル名を含む文字列を作成し、JSONでエンコードし、適切なHTTPヘッダーを持つサーバー。あなたが送信しようとしているデータがわからないし、あなたのエラーがどこから来たのかサーバー側のコードを共有していない。あなたの質問は非常に不明です。 – Quentin

+1

Node.jsにリクエストを送信せず、そのリクエストをHTTPサーバーに送信します。ノード、java、goサーバー、またはリバースプロキシのいずれでもあれば、リクエストは気にしません。 –

答えて

-2

これは現時点で私のために働いています。私が打つREST APIにはトークンが必要です。あなたはそうではないかもしれないし、他のカスタムヘッダーを探しているかもしれない。 APIのドキュメントを読んでください。ブラウザ間の互換性(約束)のためにポリフィル/シムが必要な場合があります。私はGETをやっていますが、これはPOSTでも動作します。オブジェクトを渡す必要があるかもしれません。資格情報を渡してトークンを取得する場合は、window.btoaを忘れないでください。それを次のように呼んでください:

httpReq('GET', device.address, path, device.token).then(function(data) { 
    //console.log(data); 
    updateInstrument(deviceId,path,data); 
}, function(status) { 
    console.log(status); 
}); 


    function httpReq(method, host, path, token) { 
    if(method === "DELETE" || method === "GET"|| method === "POST" || method === "PUT"){ 
     var address = 'https://' + host + path; 
     return new Promise(function(resolve, reject) { 
     var xhr = new XMLHttpRequest(); 
     xhr.open(method, address, true); 
     xhr.setRequestHeader("Accept", "application/json"); 
     xhr.setRequestHeader ("X-auth-token", token); 
     //xhr.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); 
     xhr.onload = function() { 
      var status = xhr.status; 
      if (status == 200 || status == 201 || status == 202) { 
      resolve(xhr.response); 
      } 
      // this is where we catch 404s and alert what guage or resource failed to respond 
      else { 
      reject(status); 
      } 
     }; 
     xhr.send(); 
     }); 
    } else { 
     console.log('invalid method'); 
    } 
    }; 
0

私は間違いを見つけました。これは私の問題でした。私はオブジェクトの代わりに文字列を送信しようとしていました。だから、このように、適切なJSONませんでした:

var string = JSON.stringify(suffix); 

私は追加の状況を改善するために:私は今、それ故に言葉JavaScriptオブジェクトオブジェクトを送っていたので、これは私のポストを成功させるには許さ

var newObj = JSON.stringify({link : suffix}); 

記法。

関連する問題