可以使用API GET,但不能使用API POST [英] can use API GET but not API POST
问题描述
我已经添加了一个Web API控制器类,现在我不记得了,如果它的a(v2.1 )或(v1)控制器类....无论如何,我已经调用它SyncPersonnelViaAwsApiController
我试图从AWS lambda调用它...所以如果我打电话给GET
public string Get(int id)
{
returnvalue;
}
with const req = https.request(' https:// actualUrlAddress / api / SyncPersonnelViaAwsApi / Get / 4 ',(res)=> {
我得到了返回的body:undefinedvalue
这是正确的
但是如果我试着打电话
$ p $
const req = https.request('https:// actualUrlAddress / api / SyncPersonnelViaAwsApi / SapCall',(res)=> {
我得到返回的正文:undefined {Message:请求的资源不支持http方法'GET'。}
//// POST api /< controller>
public string SapCall([FromBody] string xmlFile)
{
string responseMsg =Failed Import User;
if(!IsNewestVersionOfXMLFile(xmlFile))
{
responseMsg =不是文件的最新版本,更新没有执行;
}
else
{
Business.PersonnelReplicate personnelReplicate = BusinessLogic.SynchronisePersonnel.BuildFromDataContractXml< Business.PersonnelReplicate>(xmlFile);
bool result = Service.Personnel.SynchroniseCache(personnelReplicate);
if(result)
{
responseMsg =成功导入缓存用户;
return{\response \:\+ responseMsg +\,\isNewActiveDirectoryUser \:\\ \\false \};
$ b 有人知道它为什么适用于GET而不是POST?> p>
因为我们可以击中get im自信它不是lambda,但是我已经包含了它只是incase
const AWS = require('aws-sdk');
const https = require('https');
var s3 =新AWS.S3();
var un;
var pw;
var seralizedXmlFile;
let index =函数索引(事件,上下文,回调){
//为了测试的目的,我用对象填充了bucket和key params已经存在于S3存储桶中
var params = {
存储桶:testbucketthur7thdec,
键:personnelData_50312474_636403151354943757.xml
};
//从S3存储桶获取对象并添加到'seralizedXmlFile'
s3.getObject(params,function(data,err){
console.log 从S3桶中获取对象);
if(err){
//发生错误
}
else
{
console.log data+ data);
//用S3 bucket中的数据填充seralizedXmlFile
let seralizedXmlFile = err.Body.toString('utf-8'); //使用必要的编码
console.log(objectData+ seralizedXmlFile);
}
});
// set params
var ssm = new AWS.SSM({region:'Usa2'});
console.log('Instatiated SSM');
var paramsx = {
'Names':['/ Sap / ServiceUsername','/ Sap / ServicePassword'],
'WithDecryption':true
};
//密码和用户名
ssm.getParameters(paramsx,function(err,data){
console.log('Getting parameter');
if( err); console.log(err,err.stack); //发生错误
else {
console.log('data:'+ JSON.stringify(data)); //成功响应
console.log('password:'+ data.Parameters [0] .Value);
console.log('username:'+ data.Parameters [1] .Value);
pw = data.Parameters [0] .Value;
un = data.Parameters [1] .Value;
}
//向外部API应用程序;移除对ssl $ b $的依赖关系process.env.NODE_TLS_REJECT_UNAUTHORIZED =0;
// POST不起作用
const req = https.request('https:// actualUrlAddress / api / SyncPersonnelViaAwsApi / SapEaiCall',(res)=> {
// GET WORKS
// const req = https.request('https:// actua lUrlAddress / api / SyncPersonnelViaAwsApi / Get / 4',(res)=> {
res.headers +'授权:基本'+ un +':'+ pw;
let body = seralizedXmlFile;
console.log('seralizedXmlFile:'+ seralizedXmlFile);
console.log('Status:',res.statusCode);
console.log('Headers:',JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data',(chunk)=> body + = chunk);
res.on('end',()=> {
console.log('已成功处理HTTPS响应');
callback(null,body);
console .log('returned body:',body);
});
});
req.end();
});
};
exports.handler = index;
更新
感谢@Thangadurai发布 AWS Lambda - NodeJS POST请求和异步写入/读取文件
我能够包含post_options ...请参阅更新的lambda
//一个选项对象,用于指示在哪里发布到
var post_options = {
主机:'https:// actualUrlAddress',
端口:'80',
path:'/ api / SyncPersonnelViaAwsApi / SapEaiCall',
方法:'POST',
标题:{
'Content-Type':'application / json',
'Content-Length':post_data.length
}
};
const req = https.request(post_options,(res)=> {
res.headers +'Authorization:Basic'+ un +':'+ pw;
let body = seralizedXmlFile;
console.log('seralizedXmlFile:'+ seralizedXmlFile);
console.log('Status:',res.statusCode);
console.log('Headers: ',JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data',(chunk)=> body + = ($'$');
res.on('end',()=> {
console.log('HTTPS response has');
callback(null,body);
console.log('returned body:',body);
});
});
req.end();
现在标记为错误:
错误:getaddrinfo ENOTFOUND http:// actualUrlAddress http://actualUrlAddress.private:80
我以前有这个getaggrinfo ENOTFOUND错误,这意味着它无法找到地址....但是将主机名和api路径改为正确?
我试图达到
const req = https.request('https:// actualUrlAddress / api / SyncPersonnelViaAwsApi / SapCall
并且是端口是80
任何帮助将不胜感激
Ta
M
解决方案跳过更新部分的权利按照我的理解),选项应该如下所示:
var post_options = {
host:'actualUrlAddress',
协议:'https:'
端口:'443',
路径:'/ api / SyncPersonnelViaAwsApi / SapEaiCall',
me thod:'POST',
headers:{
'Content-Type':'application / json',
'Content-Length':post_data.length
}
};
由于 documentation 指出,主机和协议有两个独立的属性,SSL端口不太可能是80,通常是443。
Im working on an existing Windows Service project in VS 2013.
I've added a web API Controller class I cant remember now if its a (v2.1) or (v1) controller class....Anyway I've called it SyncPersonnelViaAwsApiController
Im trying to call it from a AWS lambda...so If I call the GET
public string Get(int id)
{
return "value";
}
with const req = https.request('https://actualUrlAddress/api/SyncPersonnelViaAwsApi/Get/4', (res) => {
I get returned body: undefined"value"
which is correct.
However if I try and call
const req = https.request('https://actualUrlAddress/api/SyncPersonnelViaAwsApi/SapCall', (res) => {
I get returned body: undefined{"Message":"The requested resource does not support http method 'GET'."}
//// POST api/<controller>
public string SapCall([FromBody]string xmlFile)
{
string responseMsg = "Failed Import User";
if (!IsNewestVersionOfXMLFile(xmlFile))
{
responseMsg = "Not latest version of file, update not performed";
}
else
{
Business.PersonnelReplicate personnelReplicate = BusinessLogic.SynchronisePersonnel.BuildFromDataContractXml<Business.PersonnelReplicate>(xmlFile);
bool result = Service.Personnel.SynchroniseCache(personnelReplicate);
if (result)
{
responseMsg = "Success Import Sap Cache User";
}
}
return "{\"response\" : \" " + responseMsg + " \" , \"isNewActiveDirectoryUser\" : \" false \"}";
}
Does anyone have any idea why it works for GET and not POST?
As we can hit the get im confident its not the lambda but I have included it just incase
const AWS = require('aws-sdk');
const https = require('https');
var s3 = new AWS.S3();
var un;
var pw;
var seralizedXmlFile;
let index = function index(event, context, callback) {
// For the purpose of testing I have populated the bucket and key params with objects that already exist in the S3 bucket
var params = {
Bucket: "testbucketthur7thdec",
Key: "personnelData_50312474_636403151354943757.xml"
};
// Get Object from S3 bucket and add to 'seralizedXmlFile'
s3.getObject(params, function (data, err) {
console.log("get object from S3 bucket");
if (err) {
// an error occurred
}
else
{
console.log("data " + data);
// populate seralizedXmlFile with data from S3 bucket
let seralizedXmlFile = err.Body.toString('utf-8'); // Use the encoding necessary
console.log("objectData " + seralizedXmlFile);
}
});
// set params
var ssm = new AWS.SSM({ region: 'Usa2' });
console.log('Instatiated SSM');
var paramsx = {
'Names': ['/Sap/ServiceUsername', '/Sap/ServicePassword'],
'WithDecryption': true
};
// password and username
ssm.getParameters(paramsx, function (err, data) {
console.log('Getting parameter');
if (err) console.log(err, err.stack); // an error occurred
else {
console.log('data: ' + JSON.stringify(data)); // successful response
console.log('password: ' + data.Parameters[0].Value);
console.log('username: ' + data.Parameters[1].Value);
pw = data.Parameters[0].Value;
un = data.Parameters[1].Value;
}
// request to external api application & remove dependency on ssl
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
//POST DOES NOT WORK
const req = https.request('https://actualUrlAddress/api/SyncPersonnelViaAwsApi/SapEaiCall', (res) => {
//GET WORKS
// const req = https.request('https://actualUrlAddress/api/SyncPersonnelViaAwsApi/Get/4', (res) => {
res.headers + 'Authorization: Basic ' + un + ':' + pw;
let body = seralizedXmlFile;
console.log('seralizedXmlFile: ' + seralizedXmlFile);
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
callback(null, body);
console.log('returned body:', body);
});
});
req.end();
});
};
exports.handler = index;
UPDATE
Thanks to @Thangadurai post with AWS Lambda - NodeJS POST request and asynch write/read file
I was able to include a post_options...please see updated lambda
// An object of options to indicate where to post to
var post_options = {
host: 'https://actualUrlAddress',
port: '80',
path: '/api/SyncPersonnelViaAwsApi/SapEaiCall',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
}
};
const req = https.request(post_options, (res) => {
res.headers + 'Authorization: Basic ' + un + ':' + pw;
let body = seralizedXmlFile;
console.log('seralizedXmlFile: ' + seralizedXmlFile);
console.log('Status:', res.statusCode);
console.log('Headers:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
console.log('Successfully processed HTTPS response');
callback(null, body);
console.log('returned body:', body);
});
});
req.end();
It is now flagging as error:
Error: getaddrinfo ENOTFOUND http://actualUrlAddress http://actualUrlAddress.private:80
I had this getaggrinfo ENOTFOUND error before, it means it cant find the address....but arnt the hostname and api path correct?
I am trying to reach
const req = https.request('https://actualUrlAddress/api/SyncPersonnelViaAwsApi/SapCall
and yes the port is 80
any help would be appreciated
Ta
M
解决方案 Skipping right to the update part (everything else is not relevant as I understand). Options should look like this:
var post_options = {
host: 'actualUrlAddress',
protocol: 'https:'
port: '443',
path: '/api/SyncPersonnelViaAwsApi/SapEaiCall',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
}
};
Since as documentation states, host and protocol are in two separate properties, and SSL port is very unlikely to be 80, usually it is 443.
这篇关于可以使用API GET,但不能使用API POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!