Fetch error - Receiving 405 GET Method Not Allowed While Using POST - javascript

I am trying to deploy an app where I have to register to get a JSON with my data (username, email, password) from the backend. I linked the frontend to backend with a fetch (the code is attached). My fetch request has a POST method, but I get this error, whilst I am not using any GET method, why so?
fetch('link/signup' /*will be changed with correct URL tomorrow*/,{
method: 'POST',
/* method: 'POST',
body: formData, */
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: username.value,
email: email.value,
password: password.value,
}),
}).then((response) => {
return response.json();
})
.catch((error) => {
console.log('Request failed', error);
});
GET https://link/signup/ 405 (Method Not Allowed) (anonymous) #
registration.9bbdb929a0502d2a723f.js:68

It's weird, but some APIs are not case-sensitive. Try to write 'post' instead 'POST' and see

Related

Fetch Post Request with Parameters is returning 400 status code?

I have a Post Request using fetch in react native, but I get a status code 400 for this, what is wrong with the code?
function sendRequest2() {
fetch(`https://sandbox-api.dexcom.com/v2/oauth2/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: JSON.stringify({
code: "value1",
client_id: "value2",
client_secret: "value3",
redirect_uri: "http://www.google.com",
grant_type: "authorization_code",
}),
})
.then((response) => {
response.json();
})
.then((data) => {
console.log(data);
})
.catch((err) => console.log("The error is: " + err));
}
Check your content-type, replace it by :
headers: {
"Content-Type": "application/json",
},
helpfull link : application/x-www-form-urlencoded or multipart/form-data?
You can try by removing JSON.stringify
That would solve the issue
Moreover you have shared a lot of open information regarding your server openly.
You must either hide it or add some dummy values. Sharing such a secure data openly is not recommended in open community.

Trying to use fetch instead of axios to make a POST request, but the response from the fetch request returns an error, whereas axios doesn't

I have a function which uses Axios to send a POST request which goes through successfully and I get the right response. Now I want to try using fetch to do the exact same POST request. Unfortunately, the fetch request returns a 415 Unsupported Media Type response error and I have no idea why.
Currently:
onBeforeUnload = () => {
try {
const defaultPresence = {
presence: 'AVAILABLE',
message: '',
};
const url = getServerURL() + urls.PRESENCE;
axios.post(
url,
defaultPresence,
{
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
},
);
} catch (error) {
console.log(error);
}
}
The fetch code I've used to replace the Axios POST request.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
},
body: defaultPresence,
});
fetch does not recognise plain objects as the body.
If you want to send JSON then you need to encode the data and set the content-type header yourself.
fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${getAccessToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(defaultPresence),
});

How to logout the authenticated token correctly after API call returns response?

I have the below code on client side, on click event It sends a request server side node to get a token, then when token is returned from external url response. It passes that token onto the second ajax call to call a specific api route.
This all works great, but I want to logout the token after I get the response from a specific api route (using the token). So that after the response I don't have the token staying alive.
What would be a good way to accomplish this? My current solution is when the response for the specific api route is given, send a fetch request to /tokenrequest/logout to logout the token. But not sure if that is a correct or good way to do it.
getdata.addEventListener("click", function(e) { //simple button click to initiate api
e.preventDefault();
$.ajax({
method: "GET",
url: "/jdeapi",
error: function(request, status, error) {
console.log(error);
}
}).then(function(data) {
console.log(JSON.parse(data));
let rawData = JSON.parse(data);
var token = rawData.userInfo.token;
$.ajax({
method: "POST",
url: "/sendtojde",
data: {
token
}
}).then(function(data) {
console.log(data);
})
})
})
The node server side code is as follows for the token request
router.get('/jdeapi', function(req, res) {
let url = 'https://Aisserver:port/jderest/tokenrequest';
let data = {
username: 'username',
password: 'password',
deviceName: 'riolivApp'
}
fetch(url, {
credential: 'include',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(text => res.json(text));
})
Then after the 2nd ajax call on client side, the server side call to fetch a specific api is as follows
router.post('/sendtojde', function(req, res) {
console.log(req.body.token);
let url = "https://Aisserver:port/jderest/poservice"
let data = {
token: req.body.token,
deviceName: 'riolivApp',
applicationName: "P4310",
version: "RMI0001"
}
fetch(url, {
credential: 'include',
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.text())
.then(text =>
res.json(text));
})

Node/Express - res.status().send() only sends the status but does not send an object

I am having an issue with a route in my backend where res.status().send() will only send the client the status code, but it will not send the client the object located inside of send().
Here is my code (redacted all code but the problem for brevity):
exports.user_signup = (req, res) => {
const { body } = req;
const { companyName, password, email } = body;
User.find({ email: email }, (err, previousUsers) => {
if (err) {
return res.status(400).send({
message: "There was an issue signing up."
});
} else if (previousUsers.length > 0) {
return res.status(403).send({
message: "Records show this email is linked to another account."
});
}
}
When I make my fetch request from the client, the response only returns the status code from the server, but nowhere in the response is the object in the send() method on the server. Just spitballing, I threw res.status(200).json(object) at it to send the object as json to no avail.
Here is my `fetch request from the client:
fetch("http://localhost:3000/users/accounts/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
}).then(response => console.log(response));
}
To show what response I am getting, I purposely posted some form data from the client to the route that would throw the 403 error, and this is the response I get in the browser console:
Response {type: "basic", url: "http://localhost:3000/users/accounts/", redirected: false, status: 403, ok: false, …}
So I am able to successfully send the status back from the route to the client, however I can not for the life of me figure out why send() does not send the object along with it.
The body of the response that comes back from fetch() is a ReadableStream. You need to process it to turn it into something usable. Normally you would call response.json() to parse it as a JSON object:
fetch("http://localhost:3000/users/accounts/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(response => console.log(response));
}

Vue.js Fetch throws 404 and api response

I can't make a POST request in Vue.js. It was giving me CORS issues, but I added
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
to the API and they went away. I can get valid responses from the API using Postman while using the same email and password (Postman ignores CORS).
Here is my Fetch request:
<script>
export default {
data () {
return {}
},
methods : {
login : function () {
console.log('Logging in');
// axios({
// method : 'post',
// url : 'https://www.example.com/login',
// headers : {'content' : 'application/json'},
// data : {
// email : 'emailHere',
// password : 'passwordHere'
// }
// })
// .then(function (response) {
// console.log(response);
// })
// .catch(function (error) {
// console.log(error);
// });
fetch('https://www.example.com/login', {
method: 'POST',
body: JSON.stringify({
email : 'emailHere',
password : 'passwordHere'
})
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.error(err))
}
}
}
</script>
https://www.example.com/api/v1/authenticate/login 404 (Not Found)
{status: false, message: "Invalid credentials"}
I tried Axios, and still gives me 404, but not the "Invalid Credentials" response.
In other applications I have used jquerys ajax successfully with the same API, so the API seems to allow javascript requests. But Fetch and Axios don't like it.
I have a Login.vue component that has a button
<a id="login-btn" #click.prevent="login">{{ $t('loginPage.loginButtonText') }}</a>
Any help would be appreciated! Thanks!
You are missing Content-Type header. Try setting headers in your request. Fetch demands that you set headers explicitly since it is a low-level API. Your server may reject as it doesn't recognize appropriate Content-Type. Try this:
fetch('https://www.example.com/login', {
method: 'POST',
// THIS IS IMPORTANT
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
}),
body: JSON.stringify({
email : 'emailHere',
password : 'passwordHere'
})
})
Also, remember two things with fetch:
First getting 404 using fetch doesn't mean that your request has failed. If a server responds 4xx or 5xx error, then fetch is considered successful. Only when a network error occurs, fetch is rejected. So if you get 404, it means the request has reached server but there is a problem with the client side.
Second, try setting mode to cors in you fetch request. Thought the default value of mode is cors.

Categories

Resources