fetch react native return 401 error - nginx

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'

Related

Hide token on server side with NITRO and NUXT3 for security purpose

I am using fetch to call backend API, th eprobelm is the backend security is a token, for security purpose we can not expose this token on public configuration.
I wanted to know if it is possible to put the token on server side params and then when we call fetch params is not visible in chrome debug and use only on NITRO following this text
Nitro allows 'direct' calling of routes via the globally-available $fetch helper. This will make an API call to the server if run on the browser, but will directly call the relevant function if run on the server, saving an additional API call.
$fetch API is using my fetch, with key features including:
This is my code
let recipientWebDTO = {};
recipientWebDTO.email = this.form.email;
recipientWebDTO.subscriptions = [{
"mailingListUnid": useRuntimeConfig().UNID
}];
const { status } = await $fetch
.raw(useRuntimeConfig().public.REST_API, {
method: "POST",
body: recipientWebDTO,
headers: {
"Content-Type": "application/json",
Authorization: useRuntimeConfig().TOKEN,
},
})
.then((response) => ({
status: response.status,
}))
.catch((error) => ({
status: error?.response?.status || 500,
}));
And my config file
export default defineNuxtConfig({
runtimeConfig: {
UNID: '58',
COMPANY_UNID: '3',
TOKEN: '78f77',
public: {
REST_API: process.env.REST_API || 'http://localhost:8080/rest/mailinglist/register/v1'
},
},
css: ["#/assets/_main.scss"],
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: '#use "#/assets/_colors.scss" as *;'
}
}
}
}
})
I want UNID, COMPANY_UNID, TOKEN to be visible only on server side, here it is just undefined, have I to create a middleware to handle it ? If yes, how I can use the same project to make it work ?
To manage to do it i added a server part as it is explained here:
Server api nuxtjs3 documentation
I created a directory server/api then my ts file with my proxy call where i use my token. Then in my vue i call my api. it means on browser the server file is invisible, and parameters and token nt accessibles.
in my vue:
const { status } = await $fetch.raw( '/api/newsletter', { method: "POST", body: this.form.email } )
in my server file:
export default defineEventHandler(async (event) => {
const runtimeConfig = useRuntimeConfig();
const subscriber = await readBody(event);
console.log("url used for rest call" + runtimeConfig.REST_API);
let recipientWebDTO = {
email: subscriber,
subscriptions: [{
"mailingListUnid": runtimeConfig.UNID
}]
};
const status = await $fetch.raw(runtimeConfig.REST_API, {
method: "POST",
body: recipientWebDTO,
headers: {
Authorization: runtimeConfig.TOKEN,
},
}).then((response) => ({
status: response.status,
}))
.catch((error) => ({
status: error?.response?.status || 500,
}));
return status;
})
The only complexity i have is i wanted to get a specific status but i always have the api call status, is 200 i wanted to simply forward the result but in NUXTJS is in WIP.

Drupal Webform REST

I am trying to use Drupal Webform REST.
I got an error "The 'restful post webform_rest_submit' permission is required." on browser console. I have enabled modules and REST resources as mentioned.
I used Authorization, the Auth generated in Postman, using basic auth.
I am struggling to use 'x-csrf-token' in postman.
I want to use submit the form by an anonymous user. Do I still need Authorization, will just token not work on same-origin?
const handleSubmit = async (e) => {
e.preventDefault();
await axios({
method: 'GET',
url: `${baseurl.URL}/session/token`,
headers: {
'Accept': 'application/vnd.api+json',
}
})
.then(response => response)
.then((token)=>{
console.log("CSRF TODKEN", token.data);
axios({
method: 'post',
url: `${baseurl.URL}/webform_rest/submit?_format=json`,
headers:{
'Accept': 'application/vnd.api+json',
'Content-Type': 'application/json',
'X-CSRF-Token': token.data,
'Authorization':'Basic $S$EDSnVMXDICYbVGJ'
},
data: {
"webform_id": "contact_form",
"name":name,
"email": email,
"subject": subject,
"message": message
}
})
})
.then(response => {
console.log(response)
response.status === 200 && console.log("Form successfully submitted")
})
.catch(err => console.log("SUBMIT FAIL ERROR ",err))```
It worked. I gave permission to "Access POST on Webform Submit resource" to anonymous users.

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.

React Native - How to get private posts from WordPress REST API using JWT Token

I have done logging-in WordPress Rest API with JWT Plugin passing administrator account and password and stores the received token in AsyncStorage like this.
await AsyncStorage.setItem(
'user',
JSON.stringify({
token: userData.token,
user_email: userData.user_email,
user_nicename: userData.user_nicename,
user_display_name: userData.user_display_name,
}),
);
Then I manage to get all posts including private post by including the token with request header like this,
let userInfo = await AsyncStorage.getItem('user');
let jsonUser = await JSON.parse(userInfo);
let credential = 'Bearer ' + jsonUser.token;
fetch('http://localhost/reactnativewordpress/wp-json/wp/v2/posts', {
headers: {
Authorization: credential,
},
method: 'GET',
withCredentials: true,
credentials: 'include',
})
.then(response => response.json())
.then(responseJson => {
this.setState({
items: responseJson
});
})
.catch(error => {
console.log('Error :' + error);
});
The responseJson have only public posts, no private post at all.
Thanks for help.
You need to add the
status=private
in your request,
like this http://localhost:8000/wp-json/wp/v2/posts?status=private
With that, the Authorization header should run ;)

Fetch: Can you pass parameters to the server

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
});

Resources