Localhost Fetch request failing - javascript

I have a flask api (running on host='0.0.0.0', port=8080, which should cause it to run on my priv ip), and a javascript fetch request, which when called isnt able to reach the api for some reason. The javascript is running in a webpage hosted on http://127.0.0.1:5500. Yes I have tried curl and it works perfectly. The code for the fetch request is
const lbutton = document.getElementById("lbutton");
lbutton.addEventListener("click", function() {
console.log('button clicked');
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
fetch('http://not gonna give out my ip:8080/api/log', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({email: email, password: password})
})
.then(response => {
console.log('Success:', response);
if (response.ok) {
console.log('worked');
} else {
throw new Error('Server response was not OK');
}
})
.catch(error => {
console.error('Error:', error);
});
});
Can someone explain to me why it is not working, I have been trying to figure out how to do this for ages.
I tried to make it send a POST request to my api, which should work and the api should receive login info, but the request is not making it through at all.
The fetch api is making a GET request to http://127.0.0.1:5500/login.html?email=test#gmail.com&password=test

Related

Receving "500 Internal Server Error" on Post Request to Firebase-Cloud-Function Endpoint

I'm trying to make a POST request using axios to my firebase cloud-function on form submit in react app. But I get '500' error everytime I make a request with an html-page response This app works best with javascriot enabled.
Latest Update:
It looks like there is no issue with cloud function
code. Rather more of a react-component issue. I used Postman to send
the POST request with header prop Content-Type set to application/json
and sending body in raw format {"email": "example_email"} and got
expected response from the cloud function. But when sent the request from
react component above, I get an html file response saying the app
works best with javascript enabled
I've tried setting Content-Type to both Application/json and multipart/form-data as I suspected it to be an issue but still got no luck.
Following is my code for cloud function and react submit form:
Cloud Function
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true })
const runThisFunc1 = require(./libs/runThisFunc1);
const runThisFunc2 = require(./libs/runThisFunc2);
exports.wizardFunc = functions.https.onRequest((request, response) => {
cors(request, response, () => {
let email = request.body.email;
try {
return runThisFunc1(email)
.then(data => {
console.log("Word Done by 1!");
return runThisFunc2(data);
})
.then(res => {
console.log("Word Done by 2!");
return response.status(200).send("Success");
})
.catch(err => {
console.error("Error: ", err.code);
return response.status(500).end();
});
}catch(err) {
return response.status(400).end();
}
});
});
React-Form-Component Snippet
import axios from 'axios'
...
handleSubmit = e => {
e.preventDefault()
const { email } = this.state
axios({
method: 'post',
url: `${process.env.REACT_APP_CLOUD_FUNCTION_ENDPOINT}`,
data: { email: email },
config: {
headers: {
'Content-Type': 'multipart/form-data'
}
}
})
.then(res => {
//do something with reponse here
})
.catch(error => {
console.error(error)
})
}
...
Is there something wrong I am doing in the code or the request config is wrong?

Javascript fetch not catching error, skipping past catch statement

I'm sending HTTP-requests to a server and when I receive them, I check for the status. If the status isn't 200, I want to throw the response of the server and catch it to do stuff with the error.
const handleRegistration = (nickname, email, password) => {
fetch("https://localhost:44317/api/Authentication/register",
{
method: "POST",
body: JSON.stringify({nickname: nickname, email: email, password: password}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => {
if (response.status === 200) {
location.href = "../login/login.html";
} else {
throw response.json();
}
})
.catch((response) => {
// Do something
});
};
When I register a new account where all the input fields are valid, the program works fine. But when I input data that makes for the server to return a 400 POST with as Response {"DuplicateUserName":["User name 'blabla' is already taken."]}, then I get TypeError: handleFetch(...) is undefined in my console. I'm not really sure what to do.
I've set breakpoints in the catch statement and noticed that my code never reaches it.

Axios: Send variable in the body of a POST request and not params

I am working on a project where i need to send authentication variables in the body of the request and not as parameters. I see that a POST request sends the second parameter as the body in the documentation but I am getting an error in the .NET service.
_response: "{"error":"invalid_clientId","error_description":"ClientId should be sent."}"
I was getting the same error in PHP when I wasn't send the params in the body but the values are all the same that I am using in this POST request so I know the params and values are correct.
Here is what I have:
axios.post(`https://myawesomeapi.com`,
{username:this.state.email_address, password:this.state.password, grant_type:'password', client_id:'thisAppsClientID'},
{headers: { 'content-type':'application/x-www-form-urlencoded', 'accept':'application/json' }}
).then( res => {
let result = res.data;
console.log(result);
})
.catch( (e) => { console.log(e.response); });
When I console.log and inspect the error response I see this:
config:
adapter: ƒ xhrAdapter(config)
data: "{"username":"myusername","password":"mypassword!","grant_type":"password","client_id":"thisAppsClientID"}"
headers: {Accept: "application/json, text/plain, */*", Content-Type: "application/x-www-form-urlencoded"}
...
Here is what I have in guzzle that is working if that helps:
$this->client->request('post', 'https://myawesomeapi.com',
['form_params' => ['username' => $input['username'], 'password' => $input['password'], 'client_id'=>'thisAppsClientID', 'grant_type'=>'password']],
['headers' => ['accept' => 'application/json','Content-Type' => 'application/x-www-form-urlencoded']]);
Is the username, password, grant_type, and client_id being passed as the body? Did I mess up how to send the headers? Thanks and let me know!
I know I had similar problems with axios that I never quite figured out. However, I was able to get post requests to work with Form Data. Try the snippet below. I hope it works.
const dataForm = new FormData();
dataForm.append('username', this.state.email_address);
dataForm.append('password', this.state.password);
dataForm.append('grant_type', 'password');
dataForm.append('client_id', 'thisAppsClientID');
axios.post('https://myawesomeapi.com', dataForm)
.then(res => {
let result = res.data;
console.log(result);
})
.catch(e => {
console.log(e.response);
});

JavaScript - Cannot GET /api/list

I am working on a website where a user should be able to post items to a list. Right now, when I try posting something it comes up with an error saying
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity).
When clicking on it in the console it opens a new tap where it just says
Cannot GET /api/list
Also in the command prompt, it says
Unhandled rejection Error: Can't set headers after they are sent.
Does anybody know why this might be and what I can do to fix it? Here are some snippets of my code:
Index.HTML:
fetch('/api/list', options)
.then(response => response.json())
.then(response => {
if (response.status == 'OK') {
console.log('song is added')
getList(items)
} else {
alert(response.message)
}
})
}
Server.js:
app.post('/api/list', userIsAuthenticated, (req, res) => {
let {
titleArtist
} = req.body
let user_id = req.session.user.id
// seaching for user id in database
let query = {
where: {
userId: user_id
}
}
It might also be somewhere else in the code it goes wrong. Let me know if I should post more snippets of code.
This is because you are making a GET request to POST API.
This is how you can make POST request
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

Get Token From Api Dynamically To Access Content

I need to have the token to access the content like the announcement in my code. But what i do is to copy the token generated from loginUser() and paste it inside the getAnnouncement() under the fetch. I wrote Authorization : 'Bearer esuigiugeguigiguigi' <--- this is the token. The problem with this is that i need to copy and paste again the token every time it expires.
function loginUser(){
fetch('http://sample_website.com/api/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: document.getElementById("email").value,
password: document.getElementById("password").value
})
})
.then(data => data.json() )
.then(data => {
if(data.response){
redirect: window.location.replace("../Sample/Home.html")
} else{
alert("Invalid Email or Password");
}
})
.catch((err) => {
console.error(err);
})
}
function getAnnouncement(){
fetch('http://sample_website.com/api/announcements', {
method: 'GET',
headers: {'Content-Type': 'application/json',
Authorization : 'Bearer esuigiugeguigiguigi'},
})
.then(data => data.json())
.then(data => { console.log(data)
const output = document.getElementById("display");
output.innerHTML = `<ul>
<li><h2>${data.data.data[0].title}</h2></li>
<li>${data.data.data[0].body}</li>
<li>Created: ${data.data.data[0].created_at}</li>
</ul>`;
})
.catch((err) => {
console.error(err);
})
}
Usually the response from an API call to get the token will hold:
the token
the duration of the toke
a link to refresh the token
One basic way of dealing with this is to keep the token data in localStorage or in memory or something (you can decide for yourself), and then just use it on any request that needs authorization.
It is possible that the API in question gives a specific error in case a token has expired. You can then catch it, use the link to refresh the token to get a new one, and repeat the request.
As there is not much info about the API in hand, or what you're doing and what (if any) framework you are using, this it the best answer I can provide at the moment. There are a lot of libraries out there handling this stuff already, so you might want to look into existing solutions as well.

Categories

Resources