I have to emulate curl request in nodejs:
curl -k POST https://example.com/ --cert mycert.pem:password
I already wrote some code, but it is not work similar:
request.post(
{
'url': 'https://example.com/',
'agentOptions': {
'pfx': fs.readFileSync('./mycert.pem'),
'passphrase': 'password',
}
}
)
Getting "Error: wrong tag". But it works for curl.
I will be grateful for any help.
does the following work?
const exec = require('child-process-promise').exec;
const cmd = 'curl -k POST https://example.com/ --cert mycert.pem:password';
exec(cmd).then(res => console.log(res.stdout)).catch(console.error);
So, here is solution:
request.post(
{
'url': 'https://example.com/',
'key': {
'cert': fs.readFileSync('./mycert.pem'),
'key': fs.readFileSync('./mycert.pem'),
'passphrase': 'password',
}
}
)
Still wondering, how to use "pfx" option...
Related
I've been trying for couple of days to make it calls to a endpoint of a VertexAI multiclassification in my project. But different from python that gives code the code outright for the calls to the API you need to kind read the documentation to get the result. I made it work using cURL in the command prompt. But when I try to use in javascript it doesn't seem to work properly. I have an issue with the payload of the AI. I'm using #google-cloud/aiplatform: 2.6.0 package
const cred = require("./credentials.json");
const { PredictionServiceClient } = require("#google-cloud/aiplatform");
const clientOptions = {
apiEndpoint: "us-central1-aiplatform.googleapis.com",
credentials: cred,
};
async function predict(sentences) {
const client = new PredictionServiceClient(clientOptions);
const parent = `projects/${projectId}/locations/${location}/endpoint/${endpointId}`;
const result = [];
await client.rawPredict({
endpoint: parent,
httpBody: {
instances: {
mimeType: "text/plain",
content: "Dogs rule",
},
},
});
return result;
}
I did the httpBody like this because of sample request using cURL:
curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/ui/projects/${PROJECT_ID}/locations/us-central1/endpoints/${ENDPOINT_ID}:predict -d '{
"instances": {
"mimeType": "text/plain",
"content": "YOUR_TEXT_CONTENT"
}
}'
The error I keep again(Is the same error that I get with client.predict()):
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 3,
details: 'Request contains an invalid argument.',
metadata: Metadata {
internalRepr: Map(1) { 'grpc-server-stats-bin' => [Array] },
options: {}
}
}
The question I have is how to make it work with client.rawPredict() or even client.predict().
Because is not really specific how httpBody obj should be rawPredict or the instances obj for predict()
To the request to work as it should
I've been trying (unsuccessfully) to work out how to write the following PHP code, as JavaScript:
<?php
$api_key = "abc1234567890";
$loc="https://soap.somedomain.co.uk/edi/soapsr.pl";
$uri="https://soap.somedomain.co.uk/StockQuery"; # package
$client = new SoapClient(null, array('location' => $loc,
'uri' => $uri,
'compression' => "SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | 5"
));
$stock_ids=array(1,6,15,16,167,169,170,171,172,173,175,176,5177,5178,5179,5180,5181);
$StkQtys = $client->stock_qty_array($api_key,$stock_ids);
echo var_dump($StkQtys);
unset($client);
exit;
?>
I found a jquery.soap plugin, that sounds promising, but because of my lack of understanding, I'm struggling to work out how to use the parameters above in the correct way.
I'm not sure where I should put the '$loc' and '$uri' when using $.soap()
Also, how should I structure the data: {} object to include the required information?
I've tried the following, but no luck:
<script>
function soap() {
$.soap({
loc: 'https://soap.somedomain.co.uk/edi/soapsr.pl',
url: 'https://soap.somedomain.co.uk/StockQuery',
compression: 'SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | 5'
data: {
stock_qty_array: { 'myAPIKey', {1,6,15,16,167,169,170,171,172,173,175,176,5177,5178,5179,5180,5181} }
},
success: function (soapResponse) {
console.dir(soapResponse);
},
error: function (SOAPResponse) {
console.dir(SOAPResponse);
}
});
}
</script>
When I run my code, I get the error:
POST https://soap.somedomain.co.uk/StockQuery net::ERR_FAILED
Any advice would be greatly appreciated?
Thank you, Chris
I'm using the below function in Jenkins Shared Library.
/* The below function delete uploads that exist in the server. */
def delete_upload(server_url,each_upload_id,authentication){
def delete_upload_url = server_url + "/api/v1/uploads/" + each_upload_id
def response = httpRequest consoleLogResponseBody: true,
contentType: 'APPLICATION_JSON',
customHeaders: [[maskValue: false, name: 'id ', value: each_upload_id],
[maskValue: false, name: 'Authorization', value: authentication]],
httpMode: 'DELETE', ignoreSslErrors: true, responseHandle: 'NONE', url: delete_upload_url,
validResponseCodes: '100:599'
if(response.status == 202){
def result = readJSON text: """${response.content}"""
return result['message'].toString()
}
else {
throw new Exception("Incorrect upload id! Please give the correct upload id.")
}
}
====================================================================================================
I'm getting below response,
Response Code: HTTP/1.1 202 Accepted
Response:
{"code":202,"message":"Delete Job for file with id 2","type":"INFO"}
Success: Status code 202 is in the accepted range: 100:599
====================================================================================================
Purpose: I'm using the above JSL function to delete a uploads in the web server using upload id.
Requirement:
I need to delete multiple uploads by using multiple upload id's (like each_upload_id in 1,2,3 etc) using this JSL delete function.
Need to pass the upload id's in loops and delete the uploads in the web server.
Any suggestions, please ?
Are you looking for something like this?
def idList = ["1", "2", "3"]
try {
idList.each{ id =>
delete_upload(server_url,id,authentication)
}
} catch(e) {
println "Error occurred!"
}
i'm setting a laravel and vuejs.
CORS plugin for laravel and frontend side i use Axios to call REST api
i got this ERROR
Access to XMLHttpRequest at 'https://xx.xxxx.xx' from origin
'http://localhost:8080' has been blocked by CORS policy: Response to preflight
request doesn't pass access control check: Redirect is not allowed for a
preflight request.
this is for a vuejs axios setup **main.js**
axios.defaults.baseURL = process.env.BASE_URL;
axios.defaults.headers.get['Accepts'] = 'application/json';
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.common['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept';
**content.vue file**
this.loading = true;
var companyId = this.$route.params.cid;
var userId = this.$route.params.uid;
const thisVue = this;
var formData = new FormData();
let data = {};
formData.append("subject", this.title);
formData.append("content", this.content);
formData.append("posting_article_url", this.blog_link);
formData.append("recruitment_tension", this.sel_recruitment_tension);
formData.append("why_hire_engineer", this.sel_company_hire_engineer);
formData.append("technique_skill", this.requiredTechniqueSkill);
formData.append("better_technique_skill",this.betterTechniqueSkillIfThereIs);
formData.append("personality", this.requiredPersonality);
formData.append("any_request", this.anyRequest);
formData.append("location", this.location);
formData.append("supplement_time", this.supplement_time);
formData.append("supplement_contract", this.supplement_contract);
formData.append("en_benefits", this.en_benefits);
formData.append("recruit_role", this.recruit_role);
formData.append("how_to_proceed", this.how_to_proceed);
formData.append("current_structure", this.current_structure);
if (this.selectedSkill.length > 0)
{
let selectedSkills = this.selectedSkill
.filter(obj => {
return obj.id;
})
.map(item => {
return item.id;
});
formData.append("skill_keyword", selectedSkills);
}
if (this.imageBlob != "") {
formData.append("image", this.imageBlob, "temp.png");
}
for (var i = 0; i < this.sel_schedule.length; i++) {
formData.append("freelance_type[" + i + "]", this.sel_schedule[i])
}
for (var i = 0; i < this.sel_type_of_contract.length; i++) {
formData.append("contract_type[" + i + "]", this.sel_type_of_contract[i])
}
this.loading = false;
$('html, body').animate({scrollTop:300}, 'slow');
} else {
axios
.post(
"/xx/xxx/?token=" + localStorage.getItem("token"),
formData,
{
headers: [
{ "X-localization": localStorage.getItem("lan") },
{ "Access-Control-Allow-Origin": '*' },
{ "Access-Control-Allow-Headers": 'Origin, X-Requested-With, Content-Type, Accept '},
{ "Access-Control-Allow-Methods": "POST, GET, PUT, OPTIONS, DELETE" },
{ "Access-Control-Max-Age": 3600 }
]
}
)
.then(res => {
if (!res.data.result) {
if (res.data[0]) {
this.$toaster.error(res.data[0]);
this.$store.dispatch("logout");
}
if (res.data.errors) {
for (var i = 0; i < res.data.errors.length; i++) {
this.$toaster.error(res.data.errors[i].message);
}
}
this.loading = false;
} else {
this.$toaster.success(thisVue.$t("success_recruit_add"));
}
})
.catch(() => {
this.$toaster.error(thisVue.$t("err_network"));
});
}
the error occur only one route rest all are working.
also working on Postman
Permanent solution from server side:
The best and secure solution is to allow access control from server end. For laravel you can follow the following steps:
In App\Http\Middleware\Cors.php:
public function handle($request, Closure $next)
{
return $next($request)->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods','GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS');
}
In App\Http\Kernel.php:
protected $middleware = [
...
\App\Http\Middleware\Cors::class,
];
Temporary solution from browser side:
If you want to disable CORS from browser-end then follow one of the following steps:
Safari: Enable the develop menu from Preferences > Advanced. Then select “Disable Cross-Origin Restrictions” from the develop menu.
Chrome (Extension): Use the Chrome extension Allow CORS: Access-Control-Allow-Origin
Chrome (CMD): Close all your Chrome browser and services. Then run the following command:
Windows:
“C:\Program Files (x86)\Google\Chrome\Application\chrome.exe” –-allow-file-access-from-files --disable-web-security --user-data-dir --disable-features=CrossSiteDocumentBlockingIfIsolating
Mac:
open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome — args — user-data-dir=”/tmp/chrome_dev_test” — disable-web-security
The problem comes from your Vue App.
Eg: You're requesting the url below:
https://example.com/api/methods/
And the backend redirect it to:
https://example.com/api/methods
Beware of the trailing slash at the end.
The issue is from the back-end side in our case is Laravel, in your config/cors.php try to use the below config:
'supportsCredentials' => true,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
Or you can try to use this code in the top of public/index.php
Edit
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-
Request-With');
The problem is from the server side. If you are using express js. Try to install the express cors package on your server.
npm install cors
In your app.js require cors.
var cors = require('cors')
Then, add it as a middleware to your app.
app.use(cors())
You should not experience the cors issue after installing the package.
We can fix with APP_URL, if you use it as the base url for axios request. Please, make sure your browser root url and APP_URL in .env both are same.
For example, if you run the app on "http://127.0.0.1:8000" then should be the APP_URL=http://127.0.0.1:8000
And if you run the app on "http://localhost:8000" then should be the APP_URL=http://localhost:8000
Hope, this will help! And it's tested with laravel6.x
The cors (Cross-Origin Resource Sharing) handle by server side. If you are come from laravel end so the barryvdh/laravel-cors package is help to solve this error
url:
https://packagist.org/packages/barryvdh/laravel-cors
You probably have some misconfiguration either on the webserver side or Laravel side. Perhaps this solution might help you: Why isn't my nginx web server handling ttf fonts?.
Pay close attention to the OPTIONS method, since this enables the support for Preflight.
Disabling this flag worked for me:
chrome://flags/#block-insecure-private-network-requests
nelmio_cors:
defaults:
allow_origin: ["*"]
allow_headers: ["*"]
allow_methods: ["POST", "PUT", "GET", "DELETE", "OPTIONS"]
max_age: 3600
origin_regex: false
paths:
'^/': ~
add in nelmio_cors /packge/nelmio_cors
Steps
Go to this link
https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf
download it
switch on the chrome web browser extension
Check your http link
example http to https of the remote url.
do the get api.
I think that there are plenty of similar topics here and there on the internet, but I did just spend 1h searching and still can't fix this.
I cannot make a request with POST on my server (Apache & PHP) with Angular.
I use angular/cli v.6.2.1 with node 10, apache 2.4 & php 7.1
Here is a simple code from the Http call (HttpClient & HttpHeaders both come from #angular/common/http) :
constructor(private http: HttpClient){}
this.http.post('http://localhost/distributor.php', ['prop1':'value1', 'prop2':'value2'], {headers: new HttpHeaders().set('Access-Control-Allow-Origin','*')}).subscribe(
data => {
console.log(data);
},
err => {
console.log('error');
});
}
I just try to send something back from PHP this way :
<?php
$data = $_POST;
echo json_encode($data);
I already allowed all origins in apache configuration file.
Both Firefox & Chrome just let me down after a "OPTIONS" preflight and do not do anything else, no return from the PHP file.
Here is what FireFox shows me :
and I can see this in the network tab :
Response tab shows a completely empty box.
I can remove the custom header's part from my http.post it changes nothing.
What seems strange to me is that I can click the FireFox edit & resend button, without changing nothing, and the right results appear...
Thanks for reading/help
First you need to fix your POST data; you have square brackets around Object syntax.
const data = { 'prop1': 'value1', 'prop2': 'value2' };
this.http.post('http://localhost/distributor.php', data).subscribe(
reply => {
console.log(reply);
},
err => {
console.log('error', err);
});
Next, you need to add proper headers and set PHP up to deal with JSON:
<?php
header('Access-Control-Allow-Headers: Access-Control-Allow-Origin, Content-Type');
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json, charset=utf-8');
// grab JSON data sent by Angular
$data = json_decode(file_get_contents('php://input'), true);
// add numeric data
$data["prop3"] = 3;
// reply
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK);
This worked for me.
I had the same issue but it resolved by adding these lines to your php code
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Content-Type: application/json');
let data = {
'prop1': 'value1',
'prop2': 'value2'
};
return this.http.post('http://localhost/distributor.php', data, {headers: new HttpHeaders().set('Access-Control-Allow-Origin', '*')}).map((response: Response) => {
let data = response;
if (data) {
console.log(data);
}
})