Im attempting to fetch from my localhost URL but the all the console.log() except for "done" do nothign and my .catch isnt receiving an error
fetch(tURL, {
method: 'POST',
body: JSON.stringify(post),
mode: 'cors',
headers:{
'content-type': 'application/json'
}
}).then(res => {
if (!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
form.reset();
console.log("Response received from server");
console.log(res.json);
return res.json();
})
.then(npost => {
console.log("Parsing response as JSON...");
form.style.display = '';
console.log(npost);
})
.catch(error => console.error(error));
console.log('done');
})
I put several debugging logs to see what was being reached but i get nothing
It looks like this is because of a syntax error, the }) at the end of your file should not be there, I think it is because the formatting is fairly difficult to read. If you write a .then statement between catch and console.log it will work fine. If you count the parenthesis between the fetch and the end, there is an extra set to close a block that doesn't exist. If you delete the }) at the end, your code will work, however the log statement will run before the fetch is complete; which I assume you don't want. To solve this, delete that }) and add this to the end of the chain:
.then(() => console.log('done'))
Original code
fetch(tURL, {
method: 'POST',
body: JSON.stringify(post),
mode: 'cors',
headers:{
'content-type': 'application/json'
}
}).then(res => {
if (!res.ok) {
throw new Error(`HTTP error! Status: ${res.status}`);
}
form.reset();
console.log("Response received from server");
console.log(res.json);
return res.json();
})
.then(npost => {
console.log("Parsing response as JSON...");
form.style.display = '';
console.log(npost);
})
.catch(error => console.error(error));
// This is where the error is, the catch statement was the last "block" in the callback chain, so the `})` is closing a "block" that doesn't exist.
// Delete the semicolon above and uncomment the next line to fix
// .then(() => {
console.log('done');
})
Related
I'm using the following code :-
Javascript :-
var t_sql="SELECT * FROM `compliance_report`;";
const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify( {sql: t_sql} )
};
fetch( 'test3.php', options )
.then( response => response.json() )
.then( response => {
console.log(response);
} );
The PHP code is just to echo back the Post data
:-
<?php
$sql=$_POST['sql'];
$au=json_encode($sql);
echo $au;
?>
But all I am getting back is NULL? can anyone tell me what is wrong. I ultimately want to run the query and echo back the result but the server is reporting the $_POST as empty?
This Mongoose delete method seems to work Ok locally with HttpRequester
router.delete('/', (req, res) => {
Book.findOneAndRemove({ title: req.body.title })
.then(() => res.json({ 'book deleted': 'success' }))
.catch(err => console.log('Couldn\'t delete book:', err));
}
);
but the MongoLab collection still shows the document. How to get it deleted remotely too? findOneAndDelete() didn't make a difference.
The complete repo is on https://github.com/ElAnonimo/booklist
findOneAndRemove had issues earlier.
findByIdAndRemove works fine.
router.delete('/', (req, res) => {
Book.findOne({ title: req.body.title })
.then((doc) => if(doc)return Book.findByIdAndRemove(doc._id))
.then(() => res.json({ 'book deleted': 'success' }))
.catch(err => console.log('Couldn\'t delete book:', err));
}
);
or even better you can do as follows
router.delete('/', (req, res) => {
Book.deleteOne({ title: req.body.title })
.then(() => res.json({ 'book deleted': 'success' }))
.catch(err => console.log('Couldn\'t delete book:', err));
}
);
Have you change your URI connection to MongoDB on mLab?. I think you've changed it yet.
Please sure use mongodb://<dbuser>:<dbpassword>#ds12xxxx.mlab.com:27342/[database_name], not locally 'mongodb://localhost/[database_name]'
If you've changed it, please use deleteOne https://mongoosejs.com/docs/api.html#model_Model.deleteOne, it's working well.
I'm trying to cleanup 2 collections before each test. I'm using mocha --watch to rerun tests while editing the test source files. First run always executes as expected, but consecutive runs gives Topology was destroyed error from mongodb(indicated via result of http request).
I am not really sure why deleteMany deletes my inserted object in consecutive runs.
describe('myCollection1 related tests', () => {
// myCollection1 documents should refer to a valid myCollection2 document.
var foo;
const exampleObject = {name: 'TEST OBJECT', attr1: 'TO'};
beforeEach(() => {
return Promise.all([
mongo.db('mydb').collection('myCollection1').deleteMany({}), // clear collection 1
mongo.db('mydb').collection('myCollection2').deleteMany({}) // clear collection 2
.then(() => mongo.db('mydb').collection('myCollection2').insertOne(exampleObject) // and add a sample object
.then((value) => {
foo = value.ops[0]; // save this as test specific variable so I can use it in my tests.
return Promise.resolve();
})),
]);
});
it('should create a related object', (done) => {
chai.request(server)
.post('/api/v1/foos/')
.send({ related: foo._id })
.then((res) => {
res.should.have.status(200);
res.body.should.be.an('object').with.all.keys('status', 'errors', 'data');
done();
}).catch((err) => {
done(err);
});
});
});
I spotted issue with your promise structure in beforeEach. I'm not sure it is intended or not. I'm afraid it is the culprit. I'm fixing that into below:
beforeEach(() => {
return Promise.all([
mongo.db('mydb').collection('myCollection1').deleteMany({}),
mongo.db('mydb').collection('myCollection2').deleteMany({})
]) // close the promise.all here
.then(() => collections.engines().insertOne(exampleObject)) // close `then` here
.then((value) => {
foo = value.ops[0];
return Promise.resolve();
});
});
Hope it helps
I am using axios.post but the server does not seem to receive the post-data.
This is what I have:
var baseURL = "http://localhost:8888/dbRouting.php";
var body = {
function: 'foo',
id: 'bar',
}
axios.post(baseURL, body)
.then((response) => { console.log( "Data Loaded AXIOS: " + response.data ); })
.catch(function (error) {console.log(error);});
// Data Loaded AXIOS: array(0) {
// }
This jQuery post to the same file, on the other hand, works:
$.post( baseURL, body )
.done(function( data ) {
console.log( "Data Loaded JQUERY: " + data );
});
//Data Loaded JQUERY: array(2) {
//["function"]=>
//string(3) "foo"
//["id"]=>
//string(3) "bar"
//}
The server file (dbRouting.php) is just:
<?php
var_dump($_POST);
?>
Any ideas what might be going on?
This is my way of allowing the back-end which is php to process it via $_POST. This is part of my code in vue inside method section.
Assuming you are post it to a post_url and you have an object, var myObject:
var myObject = {
property: value,
property1: value1,
property2: value2
}
Inside my vue, method section:
updateForm: function( myObject ){
var post_url = (your post url);
axios.post(post_url, makePostReady( myObject ) )
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
Then above(before axios post call) or make it a global function. I created below function to turn any object I want to send as post using axios so that it will form
property=value&poperty1=value1&property2=value2......
Below is the function:
function makePostReady( object )
{
var sentence = "";
for (var key in object) {
sentenceAdd = key + '=' + object[key] + '&';
sentence = sentence + sentenceAdd;
}
//console.log( 'sentence: ' + sentence );
return sentence;
}
After that you can var_dump( $_POST ) at your post_url to check if everything is fine. Then you can process the data as usual.
Hopefully it helps
Below is some picture to help understanding better
It seems a networking issue.
Double check the URL and the port localhost:8888/dbRouting.php on JQuery & Axios demo
Are they exactly the same?
Is your .catch fired on axios? What's the error?
is your server responding on localhost:8888?
Alternatively, you can check your server implementation using a different client (e.g. Postman https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en)
I have these 2 routes. The first one redirects me to '/add' after successful login but there Auth::check always fails and answers 'not logged'. What am I doing wrong?
Route::post('/login', function() {
$log = Input::all();
if (Auth::attempt(['user_name' => $log['username_log'], 'password' => $log['pass_log']])) {
return Redirect::intended('/add');
} else {
return View::make('index', ['log_error' => '<p class="log_error">Incorrect username or password. Please, try again!</p>']);
}
});
Route::get('/add', function() {
if (Auth::check()) {
echo 'logged';
} else {
echo 'not logged';
}
});
What you want to do is use a filter, which will check if they're logged in. If they are they can proceed as you'd like them to, otherwise redirect them to the login form.
There's more information described here: http://laravel.com/docs/4.2/routing#route-filters
But by default there is an "auth" filter, so you'd use it like this:
Route::group(['before' => 'auth', 'prefix' => 'app'], function() {
Route::intended('/app');
});
This will also help you get an understanding of it: http://laravel.com/docs/4.2/security#authenticating-users