jQuery ajax request express the server returns the data

html page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</ Head > 
< body > 
    < Script > 
        var the params = {Val: " value " } 
        $ .ajax ({ 
            type: ' the GET ' , 
            URL: ' http://127.0.0.1:3000/ ' , 
            Data: the JSON. the stringify (the params), 
            the processData: to false , // jQuery whether to process data whether data 
            contentType: ' file application / JSON ' , 
            dataType: ' JSON '
        }).then(function(ret){
            console.log(ret);
        }).catch(function(err){
            console.log(err.statusText)
        })
    </script>
</body>
</html>

express server:

Here cors remember to install plug-ins, in order to solve cross-domain

npm install cors

express server code:

var express = the require ( "express"); // introduced express 
var CORS = the require ( 'CORS' );
 var App = express (); // Create instance express 
app.use (CORS ()); // To solve cross domain problem 
app.get ( "/", function (REQ, RES) { // definition of the route is also express post delete method defined 
    var responseObject = { // may also be converted to an array of arrays JSON 
        name: "large Wei " , 
        Age: 27 
    } 
    res.json (responseObject) 
}); 

app.listen ( 3000 ); 
the console.log ( " Listening to Port 3000 ")

After starting the server, open the top of the html page requests to the data! ! ! !

 

Guess you like

Origin www.cnblogs.com/fqh123/p/11562835.html