AJAX posting issue in React JS - ajax

I have been doing React JS a while, but only front-end. Now I would like to spice it up with external data. So I tried with AXIOS / FETCH unfortunatelly both of them produced this miserable result. Here is the challenge:
fetch("http://localhost:8080/backend/datatest/src.json", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})
fetch('http://localhost:8080/backend/datatest/src.json')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log(json)
})
Its basicly a copy-paste from GITHUB of fetch, assuring nothing would go badly. "GET" function works perfectly, but i got problems with POST-ing. I keep getting back the same error mesage
POST http://localhost:8080/backend/datatest/src.json 404 (Not Found)
HOWEVER! GET works perfectly.
I am using React JS, Redux, node JS. This JSON file didnt get installed at any server. In your opinion what would be the next step.
Regards,
Koppany

Related

How can I stop external js script from stopping my fetch POST request?

My app generates a custom product page on a Shopify store. I use Vue3 for the frontend. There are other apps running js on the page, e.g. live chat, push notification pop-up, GDPR cookie bar, etc. They are injected by the platform and I can't remove them. (Btw, these js are minified and hard to read)
My app has an add bundle to cart button on the floating footer to send a POST request to my server with Fetch API. But it's blocked by these irrelevant apps. I think these apps are monitoring if a POST / GET request is sent. They assume they are working on standard product pages but not custom one like mine.
I tried to implement a block list with yett. But this passive way is not good enough. It's just a fix after the issue happens. Any way I can protect my fetch request without interfering by other js scripts?
let request = new Request('/create_new_product/', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
let vm1 = this;
fetch(request)
.then(response => response.json())
.then(data => {
console.log('Success creating variant:', data);
console.log('variant_id:', data.variant_id);
// stopped here by other apps :-(
if (data.variant_id) {
vm1.addNewVariantToCart(this.variants, data.variant_id);
vm1.$emit('clearall');
setTimeout(function(){ vm1.isLoading = false; }, 2000);
}
else if (data.Error) {
alert(data.Error);
vm1.isLoading = false;
}
})
.catch((error) => {
console.error('Error:', error);
vm1.isLoading = false;
});

Can't access local json file using axios

I'm having an issue with loading json data locally. My code worked fine when I loaded data from https://randomuser.me/api, but when I specify location of my json file locally it just returns plain HTML. Definitely doing something wrong, but can't figure it out. I use axios for ajax calls. How do I make the request correctly? My code:
export function fetchUsers () {
return {
type: 'FETCH_USER',
payload: axios.get('./users.json').then( (response) =>
console.log(response.data) )
};
}

how to make a restAPI call to laravel using react

Currently, my restAPI and my App are both hosted on XAMPP. My restAPI url is laravel.dev.
My POST route looks as so...
Route::post('/content', 'Test#save');
and my Controller...
class Test extends Controller
{
public function save()
{
return "here";
}
}
Pretty simple, but now I want to make a POST request to this route from my App. I am trying to that using react's fetch, but I do not know what URL to put since my attempt does not work...
fetch('laravel.dev', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
});
I don't care about passing anything to the route, I just want a successful call to the restAPI server. Right now I'm getting...
POST http://localhost/App/src/laravel.dev 404 (Not Found)
That is also the wrong path as well, as /App is my app and I am trying to call the restAPI server.
What do I need to change to make a successful call?
fetch needs a protocol. Right now it tries to request a "local" resource. Also, add your endpoint:
fetch('http://laravel.dev/content', {
// ...
});

RESTful Express Mongoose & Backbone - Backbone model.remove() not working

I'm developing a Node app using Express, Mongoose and Backbone with Marionette.
All routes are working well except the delete route.
If I call this.model.destroy, I always get this error:
DELETE http://localhost:3000/api/user 404 (Not Found)
The 404 is returned in Express's delete route, like if Express didn't support it, but I've seen numerous examples across the web using it.
Here's my setup:
Mongoose Schema:
var UserSchema = new mongoose.Schema(
{
name: String,
email: String,
age: Number
});
User = mongoose.model('User', UserSchema);
ExpressJS Route: (not working)
app.del('/api/user/:id', user.remove);
OR
app.delete('/api/user/:id', user.remove);
This route is called by backbone model.destroy(), but returns error 404.
ExpressJS user.js controller: (works but is not reached because of the 404 before)
exports.remove = function(req, res)
{
var id = req.params.id;
User.findById(req.params.id, function(err, user)
{
user.remove(function(err)
{
if(err) res.json(err);
res.json('all good');
});
});
};
BackboneJS Model
var User = Backbone.Model.extend({
idAttribute: "_id",
url: '/api/user/',
});
BackboneJS client View
var UserView = Backbone.Marionette.ItemView.extend(
{
template: Handlebars.compile($('#userView').html()),
events:
{
'click .delete-button': 'deleteUser'
},
deleteUser: function(event)
{
this.model.remove();
}
});
I always get this error:
DELETE http://localhost:3000/api/user 404 (Not Found)
HOWEVER it works if I use this direct ajax call:
jQuery.ajax({
url:'/api/user/' + this.model.id,
type: 'DELETE',
success:function(data, textStatus, jqXHR)
{
}
});
So, why does this work if I call the route via Ajax, if Backbone internally also uses Ajax? Why does Backbone fail to make such a simple model.destroy()?
Is there a way to configure Backbone Model.destroy method to work well like the Ajax example above? Thanks
Found the problem. Backbone model.remove() was not sending the id because I was using "url" in this way:
Backbone.Model.extend({
url: '/users',
//...
});
That will tell Backbone to use exactly /users as the URL for all actions.
To ensure sending the id using "url", one can use a function:
url: function() {
return '/list_items/' + encodeURIComponent(this.id)
}
Or even better use "urlRoot" instead of "url", let the default "url" function add the id:
urlRoot: '/users'
Working like a charm with urlRoot

Post data to RESTful Invalid HTTP status code 405

I create a method to post json data to web service :
function WishList() { }
WishList.prototype.addToWishList = function(redirectURL, postURL, userObj) {
$.ajax({
type: "POST",
url: postURL,
data: JSON.stringify(userObj),
dataType: 'json',
contentType: "application/json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
}
This is my object:
var user1 = {
ID:1,
Sex:1,
Name:"titi",
Company:"ABC",
Address:"Phnom Penh",
Email:"test.abc#gmail.com",
Phone:"011123456",
WebAccount:"test.abc#gmail.com",
Password:"123456",
GroupCustomerID:125,
Stars:1,
IsVIP:0,
PriceLevel:1,
LastDateSale:"\/Date(-62135596800000)\/",
TotalCredit:150.12,
AgingData:null,
TotalRedeemPoint:1000.00,
RedeemData:null,
ExchangeRate:155.00,
HistoryData:null
};
Calling function :
$(document).ready(function () {
var myWishList = new WishList();
$('#addToWishList').click(function(){
myWishList.addToWishList('http://www.blahblahblah.com' , 'http://blahblah/Website/Products/Product.svc/Wishlist/' , user1);
});
});
Then I got errors in my console :
"NetworkError: 405 Method Not Allowed in firefox and Invalid HTTP status code 405 , XMLHttpRequest cannot load url in chrome.
Note: When I use Rest Client of Chrome to POST to web service, it worked.
Any help would be much appreciated, thank you.
Not sure what you are using as the service on the other end but this may be due to cross domain posting. I hate to post a link and run but this may be of some use to you.
http://praneeth4victory.wordpress.com/2011/09/29/405-method-not-allowed/
Looks like they could get it working in IE but had some issues as you with the other browsers. Perhaps these couple changes will help access the service better.
This post was good at explaining the error and parts to it as well so if the above link is not helpful this one may help you diagnose the issue further.
http://www.checkupdown.com/status/E405.html
ok ok last edit, just wanted to make sure you have enough info to hopefully resolve your issue, here is a good article on the underlying problem I believe you are having..
http://www.d-mueller.de/blog/cross-domain-ajax-guide/

Resources