How to send a POST request using an html button - javascript

I want to send a POST request to the URL, for example, I want to create a database in influxdb by pressing this button.
So far I tried this but cannot make it work
<button id="post-btn">Post</button>
<script>
const button = document.getElementById('post-btn');
button.addEventListener('click', async _ => {
try {
const response = await fetch('http://00.00.000.000:2000/query', {
method: 'post',
body: {
"q=create database telecom"
}
});
console.log('Completed!', response);
} catch(err) {
console.error(Error: ${err});
}
});
</script>
The error it gives me is "Failed to fetch"

You have to deal with Cross-Origin Resource Sharing, so you need to allow your Grafana origin on the InfluxDB server side.
Anyway it looks very unsafe. If you can call create database telecom, then also other Grafana user can requests own queries, e.g. drop database telecom. Grafana should have read only access and InfluxDB should be managed outside of Grafana.

Related

How to make an axios post request that is structured like a form post request?

I am having some problems with trying to customize some code for Next-Auth, an authentication library for.Next.Js.
I want to be able to use Axios to manually make the post request rather than using a <form> element.
When I do the following, I have success.
<form method='POST' action='/api/auth/signout'>
<input name='csrfToken' value={csrfToken}/>
<button type='submit'>Submit</button>
</form>
But, when I try to do the same thing with axios, it doesn't work. I am attempting to call Next-auth's Signout endpoint, which I can do just fine using this html form element. I am expecting that the application with log the user out when calling this endpoint. When I do so with the form input, then it logs the user out. When calling the same endpoint with axios, it does not log the user out and instead nothing is happening
My axios request is
const submitForm = async () => {
if (csrfToken) {
const params = new URLSearchParams();
params.append("csrfToken", csrfToken);
try {
const response = await axios({
method: "POST",
url: "http://localhost:3000/api/auth/signout",
data: params,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}).then((res) => console.log(res));
} catch (err) {
console.log(err);
}
}
};
I have tried adding additional headers that I saw on the request that works properly, like:
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-User": "?1"
I have tried making it multipart form data, passing it simply a body of {csrfToken}, and anything else I could think of.
Any tips or things that I might be overlooking?
I can't figure out why I am unable to make this work. I am using ANTD, rather than using regular html <form> elements throughout the application and would love to be able to use that additional functionality.
Edited:
I found the solution after a lot of headache. It turns out that everything was functioning as it should have previously, but Next-Auth has an issue with updating the client-side 'session' object when you make a manual change on the server side.
I fixed this by doing the following:
const res = await axios.post("/api/auth/signout", { csrfToken }).then(
async ({ request: { responseURL } }) =>
await router
.push(responseURL)
//this is from https://github.com/nextauthjs/next-auth/issues/596#issuecomment-943453568
//force the client side to refresh and revalidate since it doesn't want to do so on its own.
.then(() => document.dispatchEvent(new Event("visibilitychange")))
.catch((err) =>
console.log("err refreshing client side session ", err)
)
);
The trick that i was missing was the document.dispatchEvent(new Event('visibilitychange'). This is the magical piece that allows you to force the client side next-auth session to sync with cookies/db.
see here for more info https://github.com/nextauthjs/next-auth/issues/596#issuecomment-943453568

Post request to JSON server through FETCH api refreshes the page

I am trying to send POST requests through fetch API to JSON-server. Function is called on a simple button click (type 'button', not 'submit'). When I replace POST request with GET request everything works like it supposed to, but with POST I have a problem. Request passes, on the JSON-server entity gets created but keeps refreshing the page after each request. Also, I don't have a response from JSON-server, google chrome says 'Failed to load response data'.
Where I'm making a mistake?
const comment = {
text: "test comment",
article_id: 3
};
console.log(JSON.stringify(comment));
const options = {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(comment)
}
fetch(`${URL_COMMENTS}`, options)
.then(response => { return response.json() })
.then(data => {
console.log(data)
});
If you use Live Server extension, try disabling that and try again.
Check out for Json sever port number running on your machine
attach the html form code
So we can try it on oru local machine to reproduce the issue.... Which help us to resolve the issue easy

Accessing 3rd party API from wix

I am trying to communicate with a 3rd party API. I wrote the API in python. I want to update the name column in the database from the Wix web page using a user form and text box. The database updates and all of the endpoints are responsive using postman to test. I think the problem resides in my JavaScript on the Wix end.
I modeled the JavaScript from the Wix example at:
https://support.wix.com/en/article/calling-server-side-code-from-the-front-end-with-web-modules
I have a back end module called placeOrder stored in orderplaced.jsw that should post the variable 'name' to the api.
import { fetch } from 'wix-fetch';
// wix-fetch is the API we provide to make https calls in the backend
export function placeOrder(name) {
return fetch("https://reliableeparts.pythonanywhere.com/user", {
method: 'post',
name: JSON.stringify({ name })
}).then(function (response) {
if (response.status >= 200 && response.status < 300){
console.log(JSON.stringify({ name }))
return response.text();}
console.log(Error(response.statusText))
return Error(response.statusText);}
);
}
The front end module waits for a button click and stores the text box in the name variable.
{
import {placeOrder} from 'backend/orderplaced.jsw';
export function button1_click(event, $w) {
placeOrder(
$w("#input1").value)
.then(function() {
console.log("Form submitted to backend.");
}
);
}
}
Output:
2
The code appears to be reaching the back end. I believe the problem is in my placeOrder function as I am not very familiar with JavaScript.
Your code seems legit. The problem is with the server. When I tried to send a POST request to that address I got a 500 Internal Server Error.
You may check this curl and test the service yourself:
curl -i -X POST -H "Content-Type:application/json" https://reliableeparts.pythonanywhere.com/user -d '{"name":"test123"}'
You are probably missing the correct object structure the server is expecting or missing proper headers to POST the server (or both...)
Make sure you're following the API this server allows

How can you make an HTTP request to fetch the status.cgi json data from a Ubiquity AirMax or AirFibre radio with javascript?

My goal is to fetch the status data from a UBNT radio (https://www.ubnt.com/) using an HTTP request. The web interface url is formatted as http://192.168.0.120/status.cgi. Making the request requires a authentication cookie. Using the cookie copied from the existing web interface I am able to successfully retrieve the data.
This is my current code using the Meteor framework.
radioHost = "http://192.168.0.120";
HTTP.call("POST", radioHost + "/login.cgi",
{
headers: {
"Content-Type": "multipart/form-data"
},
data: {
username: "ubnt",
password: "ubnt"
}
}, (err, res) = > {
if(err) return console.log(err);
var cookie = res.headers["set-cookie"][0];
HTTP.call("GET", radioHost + "/status.cgi", {
headers: {
cookie
}
}, (err, res) = > {
if(err) return console.log("Error");
console.log(res);
})
})
The above code achieves both request successfully. However the server is responding to the first with a faulty token ("set-cookie" string). Using the cookie from the existing web framework the response is correct.
Here is a library written in Python that I believe does a similar thing. https://github.com/zmousm/ubnt-nagios-plugins
I believe my problem lies within the HTTP request and the web api not cooperating with the username and password.
Thanks in advance for any help.
A direct POST request to a url is not a recommended way. When you open a browser you just don't directly login. You fetch the page and then submit/login
Not simulating this behavior may impact certain sites depending on how the server works.
So if always want to look at the simulating like a real user/browser would do, make a GET request first and then the POST.
Also capture any cookies from the first GET request and then pass the same on to the next one

NodeJS - How to get cookies from server response

I want to use nodeJS as tool for website scrapping. I have already implemented a script which logs me in on the system and parse some data from the page.
The steps are defined like:
Open login page
Enter login data
Submit login form
Go to desired page
Grab and parse values from the page
Save data to file
Exit
Obviously, the problem is that every time my script has to login, and I want to eliminate that. I want to implement some kind of cookie management system, where I can save cookies to .txt file, and then during next request I can load cookies from file and send it in request headers.
This kind of cookie management system is not hard to implement, but the problem is how to access cookies in nodejs? The only way I found it is using request response object, where you can use something like this:
request.get({headers:requestHeaders,uri: user.getLoginUrl(),followRedirect: true,jar:jar,maxRedirects: 10,},function(err, res, body) {
if(err) {
console.log('GET request failed here is error');
console.log(res);
}
//Get cookies from response
var responseCookies = res.headers['set-cookie'];
var requestCookies='';
for(var i=0; i<responseCookies.length; i++){
var oneCookie = responseCookies[i];
oneCookie = oneCookie.split(';');
requestCookies= requestCookies + oneCookie[0]+';';
}
}
);
Now content of variable requestCookies can be saved to the .txt file and can loaded next time when script is executed, and this way you can avoid process of logging in user every time when script is executed.
Is this the right way, or there is a method which returns cookies?
NOTE: If you want to setup your request object to automatically resend received cookies on every subsequent request, use the following line during object creation:
var request = require("request");
request = request.defaults({jar: true});//Send cookies on every subsequent requests
In my case, i've used 'http'library like the following:
http.get(url, function(response) {
variable = response.headers['set-cookie'];
})
This function gets a specific cookie value from a server response (in Typescript):
function getResponseCookieValue(res: Response, param: string) {
const setCookieHeader = res.headers.get('Set-Cookie');
const parts = setCookieHeader?.match(new RegExp(`(^|, )${param}=([^;]+); `));
const value = parts ? parts[2] : undefined;
return value;
}
I use Axios personally.
axios.request(options).then(function (response) {
console.log(response.config.headers.Cookie)
}).catch(function (error) {
console.error(error)
});

Categories