i got a js request to my postgresql database, i'm trying to make a registration.
I tried to send react state before that, but now i just filled it up with constant values.
It send an empty body. Body: null. GET request works, the problem happens only when i use POST request
const response = await fetch("http://localhost:8080/api/user", {
method: "POST",
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
"username": "lpkopjp",
"email": "mimiomo#mail.ru",
"password": "12345678",
"repeat_password": "12345678"
})
})
UPD: the problem was solved, i've installed cors package and added app.use(cors()); into my backend code (node.js). also you have to delete no cors mode
Related
Currently I'm working in a request to a service where I'm passing it user and password in the body.
As I understand, this information should be private, however I can see this information in the payload of the request in my browser.
const response = await fetch("https://abc.abc.com/", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: {
"user": "user",
"password": "123456"
},
});
Can anyone help me to understand what can I do?
This is normal, the browser will encrypt the traffic once it's going outside your machine.
below link may be helpful.
https://security.stackexchange.com/questions/37701/is-encryption-in-https-done-by-the-browser-or-by-the-system
Im sending a request to my local server in my react app like this
fetch("http://localhost:4000/signup", {
method: "POST",
mode: "no-cors",
body: JSON.stringify({ name: "Joe", lname: "Doe" }),
headers: {
"Content-Type": "application/json",
},
})
And the problem is that im getting empty object on the req.body on my local server.
app.post('/signup', (req, res) => {
console.log(req.body);
console.log('post request sent');
})
How could i fix it that i could see the content which is being sent from the fetch body?
You appear to have two problems here each of which, by themselves, would cause the symptoms you describe.
First, as per the documentation for req.body:
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().
You don't seem to have loaded the JSON body-parsing middleware.
Second, you said mode: "no-cors" which tells fetch to silently ignore any attempts to do anything which would require permission from CORS.
This includes setting the Content-Type: application/json header which is needed to trigger the JSON parsing middleware.
So remove mode: "no-cors" and add the cors middleware to your server-side code.
I've been trying for a couple of days now to set a cookie from my web server written in Go, and everything looks right but it just won't work.
My Set-Cookie header:
Set-Cookie: session_token=token; Path=/; Expires=Date; Max-Age=120000; HttpOnly; SameSite=Strict
I've tried editing all the values and removing and adding other fields but nothing helped. If I set my request to get and navigate directly to the link with browser cookie appears, and in Postman it is there, but when I try using fetch to get the http request it doesn't work.
I know about credentials: "same-origin" and credentials: "include" but they don't work.
Here is my js fetch code:
const log_in = (e) => {
// data entry validation and stuff
const url = "/signin";
fetch(ip + url, {
credentials: "same-origin",
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: document.getElementById("username").value,
password: document.getElementById("password").value,
}),
}).then(
() => console.log("recieved")
);
};
This is not at all what I wanted but this is how I solved my problem if somebody is in the same boat as me... Using axios.
I don't use node, yarn or whatever and using cdn gave me cors errors so I just copied the code from cdn file locally and that worked.
You can se the code here:
axios({
method: 'post',
url: ip + url,
data: {
firstName: document.getElementById("username").value,
lastName: document.getElementById("password").value
},
withCredentials: true
})
I won't mark this as an answer since I wanted to do this with fetch and no 3rd party libraries but if this is someone's last resort this works...
I'm writing a quiz app, where the frontend GETs a question from the server database using Fetch API, then sends both question and answer again via Fetch API to django on the server, which then is supposed to check against the data base if the answer is correct or not. As of now the checking doesn't change anything on the server (though in the future it'll change points for the user depending on if the answer was correct). Should I then be using PUT or POST as method?
I cannot use GET, because a GET method cannot have a body for parameters.
const setup = {
credentials: "same-origin",
method: 'PUT' or 'POST'?,
body: JSON.stringify({
"answer": 'is answer',
"question": 'is question'
}),
headers: {
"X-CSRFToken": getCookie("csrftoken"),
"Accept": "application/json",
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest"
},
};
const response = await fetch('/exercises/get_exercise', setup);
that's my fetch request. Also happy to hear any other comments on the code!
Even though you're not creating actual record on your database, I'd suggest you use POST. Think of it as you're creating a submission, or an answer record.
Possible duplicate: PUT vs. POST in REST
return fetch(`{SERVICE API URL}`, {
method: 'GET',
headers: {
'userName': "username",
'password': "password",
'content-type': 'application/json'
}
})
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
I'm trying to get service API data with authorization headers, but getting 401 - Unauthorized error and the response is Missing Request Headers.
Tried with sending authorization content with body also - getting same error 401 - Unauthorized error.
Edited:
headers: {
'userName': "xyz",
'sessionToken': "xyz................."
}
When I'm checking with Postman client it is working fine, but not with the redux-saga fetch method. Kindly help me for this.
Looks like it's a backend problem - CORS Filter configuration
If the backend is on a different server (could be on the same machine, but in a different Application Server, in other words, on a different port) you have to do some CORS Filters configurations.
The frontend code is running on a server - that means it's an application. Postman is a client, just like Google Chrome or any other browser. That's the explanation why you can do the request without any problem from Postman but unsuccessful from your frontend application.
I guess you enabled the Access-Control-Allow-Origin header on the backend
Now you have to allow your custom headers with Access-Control-Allow-Headers
Whenever I use fetch and I need to add headers to the request I do it this way:
headers: new Headers({
Accept: 'application/json',
Authorization: token,
'Content-Type': 'application/json',
}),
so you might want to try this approach, also in order to debug this issue you might want to check your Netowrk tab and verify which headers are sent with the request.
You need to add an Authorization bearer header.
For instance:
headers = new Headers({
'Authorization': `Bearer ${authorizationCodeOrCredentials}`
});
In your code:
return fetch(`{SERVICE API URL}`, {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + someValue, // Add this line
'userName': "username",
'password': "password",
'content-type': 'application/json'
}
})
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
If you are using Linux system & If you have chrome in it...
Run your chrome using following command
/opt/google/chrome/chrome --disable-web-security --user-data-dir
Try now, If everything works fine then it's CORS issue from Backend.