Fetch: Can you pass parameters to the server - fetch

I'm using a basic fetch to obtain data from an express server that queries the data from a database. So I want to do a login system, i want to send the user/password from the input fields with the fetch request. so i can perform the logical check to see if password matches the data in the server. and respond with the result.
Is it possible to do a fetch that can pass parameters?
Updated Code Below:
let fetchData = {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.state.user,
password: this.state.password
})
}
var fromServer = fetch('http://localhost:3000/', fetchData)
.then(function(response){
if( !response.ok){
throw Error (response.statusText);
}
return response.json();
})
.then(function(response) {
console.log(response);
})
.catch(error => console.log("there was an error --> " + error));
Express function
app.post('/', function(req, res){
var uname = req.body.username;
var pw = req.body.password;
console.log(uname);
console.log(pw);
});

Of course you can!
Here is an example of Fetch using a POST request:
fetch("http://example.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
name: myName,
password: myPassword
})
})
.then( (response) => {
//do something awesome that makes the world a better place
});
I've answered this question before, check this for more details:
POST Request with Fetch API?
To process the request in Express, as mentioned in your comment assuming your express server is setup to parse body requests, you can do this:
app.post('/your/route', function(req, res) {
var name= req.body.name;
var password = req.body.password;
// ...do your bidding with this data
});

Related

Where is fetch getting it's endpoint value from?

I have the following code, I am using React:
// post-post
const queryDatabase = (obj, endpoint) => {
console.log(obj);
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(obj)
};
console.log(endpoint);
fetch(endpoint, requestOptions)
.then(data => {return Promise.resolve(data)}
);
}
export {queryDatabase};
For some reason console.log(endpoint) prints the endpoint that I am passing in, e.g. "/users", "/profile" etc. However, fetch is trying to send to http://localhost:3000/users so when I try to manually pass in an endpoint I get an error about trying to post to http://localhost/http://localhost/users.
Where is fetch getting this default http://localhost:3000 value?
It's only doing this for POST requests.
The only environment variables are the following:
REACT_APP_AUTH0_REDIRECT_URI=http://localhost:3000
REACT_API_SERVER_URL=http://api.localhost
PORT=3000
I also have some other environment variables for Auth0, is Auth0 doing this? I've removed these variables for testing and still nothing.
The answer is to use the Request object and pass that through to fetch:
const requestOptions = new Request(serverUrl + endpoint, {
method: 'POST',
body: JSON.stringify(obj),
headers: new Headers({
'Content-Type': 'application/json'
})
});
Why bother... use axios or something else, fetch sucks.
EDIT:
Apparently not a problem with fetch. Whatever the case this is the fix.

mystery request proc_name= &params=

Trying to debug a new React-native application -- pretty large and it has no backend so I am trying to stub something out.
The request format is pretty foreign to me. Does anyone recognize this format or know how to handle it?
proc_name=customer_ref&params={"fields" : ["customerId"],"conditions":[{"mailAddress":"dsadsa"},{"pinCode":"ZHNhZHNh"},{"mailReceiveFlag":"1"}],"order" : ["customerCode desc"],"limit" : "1","table_name" : "Customer"}
React-native request code looks like this:
try{
let result = await fetch(apiUrl, {
method: 'POST',
headers: {
'X_contract_id': contact_id,
'X_access_token': access_token,
'Content-Type': 'application/x-www-form-urlencoded',
'charset':'UTF-8',
},
body: 'proc_name='+proc_name+'&params={'+params+'}'
}).then((response) => response.json())
.then((responseJson) => {
return responseJson.result;
})
return result;
}catch(e){
console.log(e);
}
The application errors out with Unhandled Promise Rejection before even making it to the server I whipped up. Pretty new here; am I doing something wrong at the frontend layer?
Try changing your fetch structure to be like this.
async functionName(){
try{
let result = await fetch(apiUrl, {
method: 'POST',
headers: {
'X_contract_id': contact_id,
'X_access_token': access_token,
'Content-Type': 'application/x-www-form-urlencoded',
'charset':'UTF-8',
},
body: 'proc_name='+proc_name+'&params={'+params+'}'
});
let resultjson = await result.json();
return resultjson.result;
}catch(e){
console.log(e);
}
}
https://facebook.github.io/react-native/docs/network.html

GET 200 (OK) error after axios call only before refreshing page

I have an axios call fetching some json data.
Method is get, and i need credentials to login.
checkCreds2 (username, password) {
var configJITIT = {
withCredentials: true,
method: 'get',
url: 'xxx',
dataType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
params: {
$format: 'json'
}
}
this.axios(configJITIT)
.then(function (response) {
console.log(response.config)
if (response.status === 200) {
console.log('success!')
}
})
.catch(function (error) {...})
}
Thing is, when i do the call and type in my credentials, the console logs an error: GET Status 200 (OK)
The problem is, my data is not displayed as long my request gets an error.
I have to refresh the page so the data is displayed.
It really is an error.
After refreshing the page, everything's fine.
I don't want to have to refresh the page.
Any ideas?
Your params object looks a bit strange. Did you try to use the get method from axios ? It has all the correct configuration you need, you just have to provide your additional parameters.
Example:
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

fetch react native return 401 error

So I able to successfully send a request via postman, but whenever I throw it into fetch I get back a 401 error.
export const createUser = () => {
return async (dispatch) => {
dispatch({ type: CREATE_USER });
console.log('we are in the create user function');
try {
let response = await fetch('secret.com/v1/login/signup', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'test1231273123#test.com',
password: 'Asadasd123123',
first_name: 'joe',
last_name: 'doe',
phone_number: '373738'
})
});
console.log('response ' + JSON.stringify(response));
} catch (error) {
console.log(error);
}
};
};
Here is the error I keep receiving.
response {"type":"default","status":401,"ok":false,"headers":{"map":{"access-control-allow-methods":["GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"],"access-control-allow-origin":["*"],"connection":["keep-alive"],"access-control-allow-credentials":["true"],"content-length":["188"],"content-type":["text/html; charset=utf-8"],"access-control-allow-headers":["Content-Type, Accept, Authorization"],"www-authenticate":["Basic realm=\"Restricted\""],"date":["Thu, 12 Jan 2017 16:57:58 GMT"],"server":["nginx"]}},"url":"https://secret.com/v1/login/signup","_bodyInit":{},"_bodyBlob":{}}
My backend developer believes I ran into a cross domain issue and need to setup a proxy server? "set up some proxy server (I would recommend nginx) that would proxy ajax queries to our API domain"
I think it has something to do with fetch? Ideas?
I believe you need to provide the protocol, change:
await fetch('secret.com/v1/login/signup'...
to
await fetch('http://secret.com/v1/login/signup'

Sending data as key-value pair using fetch polyfill in react-native

The following code is to make HTTP POST request with fetch polyfill:
fetch(url, {
method: 'post',
body: JSON.stringify({
token: this.state.token,
}),
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
})
.done();
This request sends data as a stringified JSON obj. Is there a way to send data as key-value pair similar to requests? post(URL, data=payload) in python.
Sounds like you want the same format as a querystring, so import/require a package like https://www.npmjs.com/package/query-string which doesn't appear to depend on any browser features and has a stringify method:
queryString.stringify({
foo: 'bar',
nested: JSON.stringify({
unicorn: 'cake',
}),
});
//=> foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D
Alternatively you could just use the relevant part of its source code, though this would still be subject to its license:
function toQueryString(obj) {
return obj
? Object.keys(obj)
.sort()
.map(function (key) {
var val = obj[key];
if (Array.isArray(val)) {
return val
.sort()
.map(function (val2) {
return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
})
.join('&');
}
return encodeURIComponent(key) + '=' + encodeURIComponent(val);
})
.join('&')
: '';
}
You can then use the return value in your body parameter in fetch:
fetch(url, {
method: 'post',
body: toQueryString({ token: this.state.token }),
});
Sure. Look at the fetch documentation in github: https://github.com/github/fetch
It uses document/DOM web, but it should be the same for react-native case - just use FormData object and append all the form fields to send.
var form = document.querySelector('form')
fetch('/users', {
method: 'post',
body: new FormData(form)
})
And:
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'post',
body: data
})

Resources