This time I will bring you a detailed explanation of node to build a server, write interfaces, adjust interfaces, and cross-domain methods. Node builds servers, writes interfaces, adjusts interfaces, and cross-domain What are the precautions? What are the following? Let’s take a look at practical cases.
I just started learning node. I am exhausted from doing this today. In the future, I can write my own interface and use it myself. I no longer have to trouble other people’s backend staff. We owe them too much over the years. I can’t say enough. I'm in tears, so I won't say more, just read on. . .
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.
We will continue to study later. . . .
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:
Detailed explanation of the use of garbage collector
Detailed explanation of Nodejs memory management steps
The above is the detailed content of Node builds servers, writes interfaces, adjusts interfaces, and explains cross-domain methods in detail. For more information, please follow other related articles on the PHP Chinese website!