POST request with nodemcu esp8266 to Discord - discord

I want to translate this code on python:
payload = {
'content': '!work'
}
header ={
'authorization':'MzkyMzQyNjEzNTasdE5NjI2.XuK7Ow.JWZZcbEoObXxPc1ef0Fb2FDo2rg'
}
r=requests.post("https://discord.com/api/v9/channels/8sdf40620670353460/messages",data=payload,headers=header)
to an arduino code so I can send POST request to a discord server using my esp8266.
I tried the ESP8266 HTTP POST exaple of this page: https://randomnerdtutorials.com/esp8266-nodemcu-http-get-post-arduino/ , but it didn't work. Could anyone help me?

Related

Django-react native (axios) Request failed with status code 403 Post

I was doing put and post operations with axios in React Native before. But then I got the following error. I'm sending cookies in the headers, but it doesn't solve the problem. Help me please.

Send request to Airvisual API with Postman

I am using react and use axios for making request to the airvisual API. However when I made the request in localhost it returned with a 404 status (I registered to Airvisual and got the key). I read Airvisual documentation and it mentioned using postman to make the request so I download postman and tried it out and the request is now success. I do not understand why it does not succeed in the first place and if I have to use postman for that API call, how do I connect it with my localhost.
Here's the code:
componentDidMount() {
axios
.get(
'api.airvisual.com/v2/countries?key=c441738e-dbc0-4f06-babc-bb126a29c19f'
)
.then((response) => console.log(response));
}

CORS error on Axios PUT request from React to Spring API

I am working on an update functionality using PUT. I have a React front end and Spring back-end API. Here is the following PUT request made from front-end:
updateStuff(username, id, stuff){
return Axios.put(`http://localhost:8080/stuff/${username}`, {stuff})
}
Controller to handle this request:
#RestController
#CrossOrigin(origins="http://localhost:3000")
public class StuffController {
#Autowired
private StuffService stuffService;
#PutMapping(path="/stuff/{username}/{id}")
public ResponseEntity<Stuff> updateStuff(#PathVariable String username,
#PathVariable long id,
#RequestBody Stuff stuff) {
Stuff response = stuffService.save(stuff);
return new ResponseEntity<Stuff>(stuff, HttpStatus.OK);
}
I am able to use the same service for GET and DELETE. I am also able to send request using REST client. But when I am trying using browser I am getting this error in console:
Access to XMLHttpRequest at 'http://localhost:8080/stuff/abc' from origin
'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource.
PUT http://localhost:8080/stuff/abc net::ERR_FAILED
Not able to figure out why its just happening for PUT request? How to resolve this? Appreciate your help and time!
EDIT:
Updated the front-end to:
updateStuff(username, id, stuff){
return Axios.put(`http://localhost:8080/stuff/${username}`, {
headers:{
'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json;charset=UTF-8',
}
})
}
Still its throwing the same error. So far Spring Security is not configured. I am just checking a simple update flow without any authentication or authorization.
EDIT 2: Request headers in browser has Access-Control-Allow-Origin: *:
I ran into a similar issue a while ago. Check if the variables of your model class in the backend have the same name as in your frontend. That fixed it for me.
The best way to deal with this cors policy is to add a proxy field in the pakage.json file.enter image description here
In reactjs application you can use your spring boot api's URL as proxy to avoid CORS issue.
package.
package.json
{
"proxy": "http://localhost:8080/",
"dependencies": {
.
.
.
}
}
axios
Axios.put(stuff/${username}, {stuff})

Firebase CORS issue

I built a react app and I have deployed it on firebase. I have been getting this error whenever user searches.
Failed to load https://food2fork.com/api/search?key=0882376145a8bcae6c3cee&q=fish&count=50: Redirect from
'https://food2fork.com/api/search?key=0882376145a8107c5946c3cee&q=fish&count=50' to
'https://www.food2fork.com/api/search
key=0882376145a8bcae390107c5946c3cee&q=fish&count=50'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'https://recipe-finder-26e0e.firebaseapp.com' is therefore not allowed access.
As I am new to this one, I am unable to figure out how to enable CORS in firebase which I think is the problem. If anyone can tell me how to enable CORS I would be grateful Thank you.
Edit: Source code link --> https://github.com/AdiBev/Recipe-Finder
Update: I didn't understand in the beginning that CORS needs to be handled by back end. Thanks to #Ben. Ayoub for explaining it to me.
If it helps for any others like me who got same problem I found a great article and some proxies are mentioned there.
link ---> https://gist.github.com/jesperorb/6ca596217c8dfba237744966c2b5ab1e
In addition to Ben. Ayoub's solution it could be worth you looking into HTTPS Callable functions if it's only your app trying to communicate with the Function and it's not part of a wider external API.
They work similar to HTTPS endpoints but get rid of the headaches of CORS.
import * as functions from 'firebase-functions';
export const listener = functions.https.onCall((data, context) => {
if (data) {
throw new functions.https.HttpsError('invalid-argument');
}
return {
some: 'json',
};
}
You don't need to use the request and response parameters like in the HTTP Endpoint Cloud Function.
It accepts JSON as it's context and returns a simple JSON object.
Edit
To answer your original question, the cloud functions can make use of CORS
import * as functions from 'firebase-functions';
const cors = require('cors')({ origin: true });
export const listener = functions.https.onRequest((req, res) => {
cors(req, res, () => {
return;
});
// cloud function logic
res.json({ some: 'json' });
});

Node/Express not finding route for Angular http json post (404)

I'm developing a new Angular client which should communicate with my Node/Express server. I'm currently trying to develop the first step aka the login. This should be an http json post. It turns out that every single time I execute that post from the client to the server, the Node/Express server doesn't find the route for my path.
On the console log of the server, for my post json request I find following stacktrace:
OPTIONS /api/auth/facebook/mobile 404 274.092 ms - 1980
Node/Express side:
My route
app.post('/api/auth/facebook/mobile', authenticationHandler.handleFacebookMobileLoginRequest);
Body parser for json is defined:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
On the Angular client side, I do:
http({
method: 'POST',
url: 'http://192.168.1.101:3000/api/auth/facebook/mobile',
headers: { 'Content-Type': 'application/json; charset=UTF-8;' },
data: {fbToken: authResponse.accessToken}
})
.then(function (response) {
...
Fun facts:
Same route works fine when I call it from a Java app or and Android native app, like
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, SERVER_URL + "/api/auth/facebook/mobile", params, jsonRequestListener, errorListener);
On my Angular client, when I change data with params then it works, the route is found...but I mean that doesn't make any sense. Moreover, I've got then a problem on the Angular client side, the answer isn't processed respectively the answer never land in the .then(... function. Which again works well in other clients.
Anyone got an idea, a clue or should I call Dr. Strange?
Possible browser preflighted request CORS issue?
Try using CORS module in Node.js server:
var cors = require('cors')
app.use(cors());

Resources