as the title says, I am trying to fetch this URL from node/express server. The route is working fine in Postman, so I believe it tells me the mistake is in my fetch method.
my code:
onSubmitSave = () => {
fetch('http://localhost:3000/profile/:id', {
method: 'put',
headers: {'Content-Type': 'application/json' },
body: JSON.stringify({
name: this.state.name,
telephone: this.state.telephone,
})
})
.then(response => response.json())
.then(user => {
console.log(user);
}).catch(err => console.log(err))
}
I would be glad if anyone could help me with that.
I don't see your :id being replaced by any string interpolation. You might be looking for something like this:
fetch(`http://localhost:3000/profile/${this.id}`)
Related
i am writing a simple user register using Laravel with a simple code
public function register()
{
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required'
]);
$user = User::create(request(['name', 'email', 'password']));
auth()->login($user);
return [
'status' => true,
'user' => $user
];
}
then i am sending the data form Next.Js :
using axios:
let config = {
method: 'post',
url: `http://localhost:8000/api/register`,
headers: {
'Content-Type': 'application/json',
},
data: values,
}
axios(config)
.then(json => console.log(json))
it's work fine, but i send an used email address, it will through 422 code, and axios can't catch the result
using fetch:
fetch('http://localhost:8000/api/register', {
method: "post",
mode: 'no-cors',
body: new URLSearchParams(data)
}).then(res => res.json())
.then(json => console.log(json))
also work but when use used email, it will send 302 code , and call the index /
I think that you have missed adding the .catch(...) to return the error object like the example in docs
Axios docs
http POST http://localhost:8000/api-auth-token/ username="saadman" password="Sakib123#"
It works fine when i run it on terminal.
Now, I am trying to implement equivalent code in javascript to fetch authtoken:
fetch('http://localhost:8000/api-auth-token/',{
method:'POST',
header:{
username: 'saadman'
password: 'Sakib123#'
}
}
But it's not working
finally this worked for me:
var raw = JSON.stringify({"username":"saadman","password":"Sakib123#"});
var requestOptions = {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: raw,
redirect: 'follow'
};
fetch("http://192.168.43.189:8000/api-auth-token/", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I am working on a website and I am trying to write a script which sends data once someone creates an account. But I get some errors(attached a screenshot) and can't find a way to fix them as I'm still an intern. Hopefully someone can help me.
Thank you.
if (val2 == 1) {
fetch(hookURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
body: attrString,
mode: 'no-cors'
})
.then((response) => {
//console.log('hook returned, response= ', response);
});
enter image description here
If You want to send data - use a different method ;)
Try POST instead of GET
Look at the below example from:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
I have an event like below:
handleDownload(e) {
e.preventDefault();
alert('Hi');
let communityName = this.state['selectedCommunity'];
let files = this.state[files];
fetch(clientConfiguration['filesApi.local'], {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ communityName: communityName, body: files })
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err))
};
I have a button as below:
renderDownloadButton() {
if (this.state.files && this.state.files.filter(i => i.checked).length) {
return (
<button id="download" styles="display: none;" onClick={this.handleDownload} >
Download
</button>
);
}
};
It fires but it is giving following error, any help please - thank you. At
let communityName = this.state['selectedCommunity'];
its giving me the error;
Can not read property state undefined
Any help please?
My guess is that you need to bind your handler, but it's really hard to tell without whole component code.
handleDownload = (e) => {
e.preventDefault();
alert('Hi');
let communityName = this.state['selectedCommunity'];
let files = this.state[files];
fetch(clientConfiguration['filesApi.local'], {
method: 'POST',
headers: new Headers(),
body: JSON.stringify({ communityName: communityName, body: files })
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err) => console.log(err))
}
For the api post not fetching the error can be one possible case of CORS error that browser do not allow you to access other network(private and secured IP address) so you need to actually allow the proxy setting as I can see your post data don't have any proxy enabled. Here is the code I am attaching
This is the pseudo code please make changes accordingly in your fetch method:
var targetUrl ='/downloadableReport'
const res= fetch(targetUrl,{
method: 'POST',
headers: {
'Content-Type': "application/json; charset=utf-8",
},
body: JSON.stringify({
"requestData":{
"userName":"XXX",
"password":"XXXX",
"clientId":"XXXX",
"txnType":"XXXX"
}
})
})
.then(response => response.json())
.catch(error =>{
console.log(error)
})
Also, you need to add setupProxy.js file (mind the name of the file should be this only) and add this code (with preferred changes)
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(
proxy("/downloadableReport",{
target:"http://192.168.1.220:8080/report/abc" ,
changeOrigin:true
})
)
};
I'm fetching data from my API using this. It will post email and password to my API
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
.then(response => response.json())
.then(data => {
if (data === 'login success') {
this.props.onRouteChange('home');
}
})
.catch((e) => console.log(e))
};
and the request will be handled in the API by this
app.post('/signin', (req, res) => {
if (req.body.email === db.users[0].email && req.body.password === db.users[0].password) {
res.json('login success')
} else {
res.json('login fail')
}
});
This will result in TypeError: NetworkError when attempting to fetch resource.
However, if the .then are removed and the this.props.onRouteChange('home'); is added below like this
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
this.props.onRouteChange('home');
};
it will work and I can log in without errors.
But, the same error will still be shown if this.props.onRouteChange('home'); is removed like this
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
};
I've also double checked my API with Postman and the post request was successful.
This a odd problem for me and I'm new to javascript, please forgive me if this happens to be a careless newbie mistake. Thanks.
P.S. Please let me know if more code is needed.
Are you running the app on the same client that's hosting it? Try changing localhost to your client's LAN IP and see if that makes a difference?