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.
Related
I'm trying to make a post request from a webpage to a Wildfly Camunda server to start a task. It works using postman with localhost:8080/engine-rest/message, but when I use the webpage all I get is Type error: failed to fetch. I have tried just using localhost:8080/engine-rest/message but gets:
Fetch API cannot load localhost:8080/engine-rest/message. URL scheme must be "HTTP" or "HTTPS" for CORS request.
/* And */
Error: TypeError: Failed to fetch at HTMLFormElement.<anonymous>
And if I set mode : no-cors I get Fetch API cannot load localhost:8080/engine-rest/message. URL scheme "localhost" is not supported. and Error: TypeError: Failed to fetch at HTMLFormElement.<anonymous>
const form = document.getElementById('myForm');
form.addEventListener('submit', function() {
// alert("Request sent");
const urlHttp = 'http://localhost:8080/engine-rest/message';
const url = "localhost:8080/engine-rest/message";
const data = {
messageName: 'start',
businessKey: '7'
};
// send POST request
fetch(urlHttp, {
method: 'POST',
// mode : 'no-cors',
headers: {
'Content-Type': 'application/json; charset=UTF-8;',
// 'Accept' : 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
});
I created backend where it will accept requests to the following url
http://10.1.0.1/cgi-bin/api/write_config
With Postman I get the appropriate response but when I try the same thing with fetch, I get a network error
This is my code:
fetch ('http://10.1.0.1/cgi-bin/api/write_config', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
param1: 'attr1',
param2: 'attr2',
param3: 'attr3',
}),
})
.then(response => {
console.log(response.json())
return response.json()
})
.then(data => {
console.log(data)
})
.catch(e => {
console.log('In catch block')
console.log(e)
})
These are the header I'm getting from the response (in Postman):
Content-Type: application/json
Access-Control-Allow-Origin: *
I'm getting the following error (in Javascript):
{ [TypeError: Network request failed] line: 24117, column: 31,
sourceURL:
'http://localhost:8081/index.delta?platform=android&dev=true&minify=false'
}
Edit:
I configured the Raspberry Pi in the same way in which I configured the other device then the output is correct. Is it some certificate issue with Javascript?
If you are using the Android Emulator try to use your IP Address instead of 10.1.0.1 - I had network request errors too but it worked with my IP.
did u tried console.log(body) ? sometimes JSON not work. if u don't have problem with body . I'm sure header is wrong
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));
}
I have written an authentication service in Angular 5 which does a POST request to my backend using the HttpClient class. The backend responds by sending a JWT bearer token.
My request looks like this:
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
'username': username,
'password': password
}, {
headers: new HttpHeaders()
.set('Content-Type', 'application/json')
})
.toPromise()
.then(response => {
console.log(response);
return response;
});
}
How do I access the authorization header of the response?
When I write the response to the console, like above, it says 'null'. I know the error is not in the backend because I captured the traffic and the backend is indeed sending the bearer token.
Any help is very much appreciated.
To access the full response (not just the body of the response), you must pass the observe: 'response' parameter option in your http request. Now you can access the headers with res.headers
return this.http.post('http://127.0.0.1:8080/api/v1/login', {
'username': username,
'password': password
}, {
headers: new HttpHeaders()
.set('Content-Type', 'application/json'),
observe: 'response'
})
.map(res => {
let myHeader = res.headers.get('my-header');
});
Docs
I have a fetch request within the componentDidMount() method of a React component:
const request = new Request(url, {
mode: 'no-cors',
method: 'get',
headers: {
Accept: 'application/json'
}
});
fetch(request)
.then(function(response) {
console.log('Response: ', response);
return response.text();
})
.then(function(data) {
// _this.setState({ data: data });
console.log('Success: ', data);
console.log('Request succeeded with JSON response', data);
}).catch(function(error) {
console.log('Request failed', error);
});
When the Component loads, I can see the Request being made in the Console and the proper data being returned; however, my Response object is always empty:
Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, bodyUsed: false }
response.text() returns null, and I'm really uncertain what is going on. I've used the same method before and not had this problem, so I'm uncertain if it's different because of the third-party data source or what.
Any ideas?
I suggest you to follow the comments below the question:
sideshowbarker says
If the reason you’re using mode: 'no-cors' is because the server doesn’t send the Access-Control-Allow-Origin response header in its responses, then mode: 'no-cors' is not the way to fix that. The only way to fix it properly is to either configure the server to send Access-Control-Allow-Origin response header or else change your frontend JavaScript code to make you request through a proxy instead. follow this link...