This time I will show you how to use node to build a server, write interfaces, adjust interfaces, cross-domain, use node to build servers, write interfaces, adjust interfaces, cross-domain What are the precautions, below This is a practical case, let’s take a look at it. .
In the server project directory:
1. Create a package.json file with npm init;
2. Create a The app.js file has the following annotations. I simply wrote an interface, which will be used below, and set up cross-domain access.
var express=require('express'); var app =express(); //设置跨域访问 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1'); res.header("Content-Type", "application/json;charset=utf-8"); next(); }); var questions=[ { data:213, num:444, age:12 }, { data:456, num:678, age:13 }]; //写个接口123 app.get('/123',function(req,res){ res.status(200), res.json(questions) }); //配置服务端口 var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); })
3. Next, it’s time to install express FrameworkOkay, because we used it above, install it directly and write it into the dependencies.
npm install express --save
Under the project directory:
1. Create an index.html file and make an ajax get request. The url is The interface address of the server we just created.
$.ajax({ type:'get', url:'http://localhost:3000/123', success:function(data){ console.log(data); }, error:function(){ console.log('error'); } })
2. Looking at the picture below, you can see that we have requested the data, and you can do whatever you want with the data.
# I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use Nodejs memory management
The above is the detailed content of How to use node to build a server, write interfaces, adjust interfaces, and cross domains. For more information, please follow other related articles on the PHP Chinese website!