gpt4 book ai didi

javascript - 使用来自客户端的信息进行 Node Js/Express api 调用

转载 作者:行者123 更新时间:2023-11-28 18:57:34 27 4
gpt4 key购买 nike

所以我正在编写一个web应用程序来从steam api获取信息,并且我遇到了一些cors问题,所以我编写了一个node/express服务器来执行实际的api调用,然后客户端应用程序从我的服务器获取json 。这是有效的,但前提是 api 调用在我的服务器上进行了硬编码。如何从客户端的“sid”表单字段向服务器提供用户 ID?

服务器代码:

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

var app = express();
function proxy(){
app.use('/', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
var apiServerHost = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=[APIKEY]&steamids=";
var userId = 76561197972495328;
var url = apiServerHost+userId;
req.pipe(request(url)).pipe(res);
});
}

proxy();


app.listen(process.env.PORT || 3000);

客户端代码:

function submit(){
$(document).ready(function(){
var sid = document.getElementById("idform").elements[0].value;
$.getJSON("http://localhost:3000/", function(result){
console.log(result);
console.log(result.response.players[0]);
for(i in result.response.players[0]){
document.getElementById("main").appendChild(document.createTextNode(i + " : " + result.response.players[0][i]));
document.getElementById("main").appendChild(document.createElement("br"));
}
});
});
}

最佳答案

试试这个:

服务器代码:

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

var app = express();
function proxy(){
app.use('/', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
var apiServerHost = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=[APIKEY]=";
var userId = encodeURIComponent(req.query.sid);
var url = apiServerHost+userId;
req.pipe(request(url)).pipe(res);
});
}

proxy();


app.listen(process.env.PORT || 3000);

客户端代码:

function submit(){
$(document).ready(function(){
var sid = document.getElementById("idform").elements[0].value;
$.getJSON("http://localhost:3000/?sid=" + encodeURIComponent(sid), function(result){
console.log(result);
console.log(result.response.players[0]);
for(i in result.response.players[0]){
document.getElementById("main").appendChild(document.createTextNode(i + " : " + result.response.players[0][i]));
document.getElementById("main").appendChild(document.createElement("br"));
}
});
});
}

关于javascript - 使用来自客户端的信息进行 Node Js/Express api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323716/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com